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>

本文由 hcb 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

2 条评论

  1. wthglwhfle
    wthglwhfle

    探秘传奇私服妖兽大陆,怪物挑战等你来战,赢取独家福利!:https://501h.com/yuanshi/2024-11-05/46447.html

  2. gpsylxfshl
    gpsylxfshl

    《美好的一天》剧情片高清在线免费观看:https://www.jgz518.com/xingkong/107.html

添加新评论