jpa官网: https://spring.io/projects/spring-data-jpa
mybatis官网: https://mybatis.org/mybatis-3/
中文版: https://mybatis.org/mybatis-3/zh_CN/index.html
相同点:
都是java中用于持久化数据的框架
不同点:
JPA是基于对象的编程模型,MyBatis是基于SQL语句的编程模型。
JPA使用JPQL (Java Persistence Query Language)作为查询语言,而MyBatis使用SQL作为查询语言
jpa
//基于注解的命名查询配置
@Entity
@NamedQuery(name = "User.findByEmailAddress",
query = "select u from User u where u.emailAddress = ?1")
public class User {
}
//UserRepository 中的查询方法声明
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByLastname(String lastname);
User findByEmailAddress(String emailAddress);
}
//@Query 将查询与存储库接口放在一起
public interface UserRepository extends JpaRepository<User, Long> {
@Query("select u from User u where u.emailAddress = ?1")
User findByEmailAddress(String emailAddress);
}
//like
public interface UserRepository extends JpaRepository<User, Long> {
@Query("select u from User u where u.firstname like %?1")
List<User> findByFirstnameEndsWith(String firstname);
}
//@Query 在查询方法中声明本机查询
//允许通过将nativeQuery标志设置为 true 来运行本机查询
public interface UserRepository extends JpaRepository<User, Long> {
@Query(value = "SELECT * FROM USERS WHERE EMAIL_ADDRESS = ?1", nativeQuery = true)
User findByEmailAddress(String emailAddress);
}
//声明用于分页的原生计数查询@Query
public interface UserRepository extends JpaRepository<User, Long> {
@Query(value = "SELECT * FROM USERS WHERE LASTNAME = ?1",
countQuery = "SELECT count(*) FROM USERS WHERE LASTNAME = ?1",
nativeQuery = true)
Page<User> findByLastname(String lastname, Pageable pageable);
}
//使用命名参数
//@Param注释为方法参数赋予一个具体的名称,并在查询中绑定该名称
public interface UserRepository extends JpaRepository<User, Long> {
@Query("select u from User u where u.firstname = :firstname or u.lastname = :lastname")
User findByLastnameOrFirstname(@Param("lastname") String lastname,
@Param("firstname") String firstname);
}
mybatis
1.安装
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>x.x.x</version>
</dependency>
还不快抢沙发