Home  >  Article  >  Java  >  How to use SpringBoot JPA common annotations

How to use SpringBoot JPA common annotations

WBOY
WBOYforward
2023-05-13 09:40:191028browse

    1. Introduction

    Jpa is a set of ORM specifications
    hibernate is not just an ORM framework Provides implementation of JPA

    JPA (Java Persistence API): java persistence API

    2. Common annotations

    2.1 @ Entity

    marks the current class as an entity class and will be mapped to the specified database table

    @Entity
    public class Users {
    		
    }

    2.2 @Table

    is generally annotated together with @Entity Use, if the database table name and class name are consistent, it is okay not to use the @Table annotation,
    Otherwise, you need to use the @Table annotation to specify the table name

    @Entity
    @Table(name="t_users")
    public class Users {
    		
    }

    2.3 @Id, @GeneratedValue, @SequenceGenerator, @Column

    2.3.1 @Id

    is used to map the attributes of the entity class to the primary key

    2.3.2 @ GeneratedValue

    Specify the primary key generation strategy

    package javax.persistence;
    /**
     * 策略类型
     */
    public enum GenerationType {
      /**
       * 通过表产生主键,框架借由表模拟序列产生主键,使用该策略可以使应用更易于数据库移植
       */
      TABLE,
      /**
       * 通过序列产生主键,通过 @SequenceGenerator 注解指定序列名
       * MySql 不支持这种方式
       * Oracle 支持
       */
      SEQUENCE,
      /**
       * 采用数据库 ID自增长的方式来自增主键字段
       * Oracle 不支持这种方式;
       */
      IDENTITY,
      /**
       * 缺省值,JPA 根据数据库自动选择
       */
      AUTO;
    
      private GenerationType() {
      }
    }
    2.3.3 @SequenceGenerator
    2.3.4 @Column

    When the entity class attribute name and the database column name are inconsistent This annotation must be used

    @Entity
    @Table(name="t_users")
    public class Users {
    
      @Id
      @Column(name = "user_id")
      @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_seq")
      @SequenceGenerator(name = "user_seq", sequenceName = "user_seq")
      private Long userId;
    		
    }

    2.4 @Transient

    Indicates that the current attribute does not need to be mapped to the database

    2.5 @Temproal

    Mainly for Date type attributes Use, you can specify the precision of the time through this annotation

    @Entity
    @Table(name="t_users")
    public class Users {
    
      @Temporal(TemporalType.DATE) 
      private Date time1;
      
      @Temporal(TemporalType.TIME)
      private Date time2;
      
      @Temporal(TemporalType.TIMESTAMP)
      private Date time3;
    }

    3. EntityManagerFactory

    is similar to hibernate's SessionFactory

    4. Four types of EntityManager entities Status

    New status: The new creation does not yet have a persistent primary keyPersistence status: Already has a persistent primary key and has established a context relationship with persistence Free state: Has a persistent primary key, but has no context relationship with persistence Deletion state: Has a persistent primary key, and has a context relationship with persistence, but has been deleted from the database

    4.1 find(Class entityClass, Object primaryKey)

    Similar to get() of session in hibernate

    find will return null if no query is found

    4.2 getReference(Class entityClass, Object primaryKey)

    Similar to the load() of session in hibernate
    Only when the attributes in the object are actually obtained, the query will be executed. sql statement, getReference() just returns a proxy object

    getReference will not return null if it is not queried, and will throw EntityNotFoundException

    Note: Using this method may A lazy loading exception occurs, that is, we have not yet obtained the attribute value in the entity class, and the EntityManager has been closed as a result.

    4.3 persist

    Similar to Save() of session in hibernate

    Note: The object passed in when executing the method cannot set the primary key value and an exception will be thrown

    4.4 remove

    Similar to delete() of session in hibernate

    Note: This method can only delete persistent objects, but not free objects (hibernate can)

    	/**
    	 * 删除游离态(失败)
    	 */
    	public void testRemove(){
    		Users user = new Users();
    		Users.setUserId(1);
    		entityManager.remove(customer);
    	}
    	
    	/**
    	 * 删除持久化状态(成功)
    	 */
    	public void testRemove(){
    		Users user = entityManager.find(Users.class, 1);
    		entityManager.remove(user);
    	}

    4.5 merge(T entity)

    Similar to saveOrUpdate() in session in hibernate

    	// 新建状态
    	public void testMerge	(){
    		Users user= new Users();
    		// 省略一系列的set
    		// user.set.....
    		Users newUser = entityManager.merge(user);
    		// user.getUserId() == null  ==> true
    		// newUser.getUserId() == null ==> false
    	}

    How to use SpringBoot JPA common annotations

    4.6 flush()

    Similar to flush() in session in hibernate

    Save all unsaved entities in the context to the database

    4.6 refresh()

    Similar to session refresh() in hibernate

    Refresh the attribute values ​​of all entities

    5. EntityTransaction

    EntityManager.getTransaction()

    5.1 begin

    5.2 commit

    5.3 rollback

    6. Mapping relationship

    6.1 One-way one-to-many

    Take the relationship between users and orders as an example. A user has multiple orders, and one order only belongs to one user
    For a pair When inserting multiple relationships, whether the many side or the one side is inserted first, an additional update statement will be generated, because the many side will not insert the foreign key column during the insert

    /**
     * 订单和用户是多对一的关系
     */
    @Entity
    @Table(name="t_order")
    public class Order {
    	// lazy为懒加载,默认为eager立即查询
    	@ManyToOne(fetch=FetchType.Lazy)
    	// @JoinColumn标注字段是一个类,userId为该类的主键
    	@JoinColumn(name="user_id")
    	private Users user;
    }

    6.2 One-way Many-to-one

    Take the relationship between users and orders as an example. A user has multiple orders, and an order only belongs to one user
    For inserts in a many-to-one relationship, it is best to first The end that saves one and then the end that saves many.
    If you save the many end first and then the one end, in order to maintain the foreign key relationship, you need to perform additional update operations on the many end

    /**
     * 订单和用户是多对一的关系
     */
    @Entity
    @Table(name="t_order")
    public class Order {
    	// lazy为懒加载,默认为eager立即查询
    	@ManyToOne(fetch=FetchType.Lazy)
    	// @JoinColumn标注字段是一个类,userId为该类的主键
    	@JoinColumn(name="user_id")
    	private Users user;
    }

    6.3 Two-way many-to-one

    Take the relationship between users and orders as an example. A user has multiple orders, and an order only belongs to one user.
    Two-way many-to-one is a combination of the above two, using @OneToMany and @ManyToOne

    /**
     * 用户和订单是一对多的关系
     */
    @Entity
    @Table(name="t_users")
    public class User {
    	// 如果两侧都要描述关联关系的话,维护关联关系的任务要交给多的一方
    	// 使用 @OneToMany 了 mappedBy 的代表不维护关联关系,也就是不会产生额外的update语句
    	// @OneToMany 和 @JoinColumn 不能同时使用会报错
    	@OneToMany(mappedBy="user")
    	private Set orders;
    }
    
    /**
     * 订单和用户是多对一的关系
     */
    @Entity
    @Table(name="t_orders")
    public class Order {
    	// lazy为懒加载,默认为eager立即查询
    	@ManyToOne(fetch=FetchType.Lazy)
    	// @JoinColumn标注字段是一个类,userId为该类的主键
    	@JoinColumn(name="user_id")
    	private Users user;
    }

    How to use SpringBoot JPA common annotations

    6.4 双向一对一

    以学校和校长之间的关系为例,一个学校只有一个校长,一个校长也只属于一个学校
    一方使用 @OneToMany + @JoinColumn,另一方使用 @OneToOne(mappedBy=“xx”)
    具体由哪一方维护关联关系都可以,这里我们以学校一端维护关联关系为例
    保存时先保存不维护关联关系的一方(也就是使用@OneToOne(mappedBy=“xx”)的一方),否则会产生额外的 update 语句

    /**
     * 学校
     */
    @Entity
    @Table(name="t_school")
    public class School {
    	// 默认为eager立即查询
    	@OneToOne
    	// 添加唯一约束
    	@JoinColumn(name="school_master_id", unique = true)
    	private SchoolMaster schoolMaster;
    }
    
    /**
     * 校长
     */
    @Entity
    @Table(name="t_school_master")
    public class SchoolMaster {
    	// 不维护关联关系要使用 mappedBy
    	@OneToOne(mappedBy="schoolMaster")
    	private School school;
    }

    6.5 双向多对多

    以学生和课程之间的关系为例,一个学生可以选多门课,一个课程也有多个学生,多对多需要一个中间表,也就是选课表
    维护关联关系的一方需要使用 @JoinTable
    关联关系也是只有一方维护即可,这里我们由学生表进行维护

    /**
     * 学生
     */
    @Entity
    @Table(name="t_student")
    public class Student {
    	@GeneratedValue
    	@Id
    	private Long student_id;
    	
    	// 要使用 set 集合接收
    	// 默认为lazy懒加载
    	@ManyToMany
    	// name 为中间表的表名
    	@JoinTable(name="t_student_choose_course",
    			// name 为与中间表与当前表所关联的字段的名称,referencedColumnName 为当前表中与中间表关联的字段的名称
    			joinColumns={@JoinColumn(name="student_id", referencedColumnName="student_id")},
    			// name 为与中间表与多对多另一方表所关联的字段的名称,referencedColumnName 为多对多另一方与中间表关联的字段的名称
    			inverseJoinColumns={@JoinColumn(name="course_id", referencedColumnName="course_id")})
    	private Set courses;
    }
    
    /**
     * 课程
     */
    @Entity
    @Table(name="t_course")
    public class Course {
    	@GeneratedValue
    	@Id
    	private Long course_id;
    	
    	// 要使用 set 集合接收
    	// 默认为lazy懒加载
    	@ManyToMany(mappedBy="courses")
    	private Set students;
    }

    7. 二级缓存

    开启了二级缓存之后,缓存是可以跨越 EntityManager 的,
    默认是一级缓存也就是在一个 EntityManager 中是有缓存的
    二级缓存可以实现,关闭了 EntityManager 之后缓存不会被清除
    使用 @Cacheable(true) 开启二级缓存

    8. JPQL

    8.1 查询接口

    8.1.1 createQuery
    	public void testCreateQuery(){
    		// 这里我们使用了一个 new Student,因为我们是查询 Student 中的部分属性,如果不适用 new Student 查询返回的结果就不是 Student 类型而是一个 Object[] 类型的 List
    		// 也可以在实体类中创建对应的构造器,然后使用如下这种 new Student 的方式,来把返回结果封装为Student 对象
    		String jpql = "SELECT new Student(s.name, s.age) FROM t_student s WHERE s.student_id > ?";
    		// setParameter 时下标是从1开始的
    		List result = entityManager.createQuery(jpql).setParameter(1, 1).getResultList();
    	}
    8.1.2 createNamedQuery

    需要在类上使用 @NamedQuery 注解,事先声明 sql 语句

    @NamedQuery(name="testNamedQuery", query="select * from t_student WHERE student_id = ?")
    @Entity
    @Table(name="t_student")
    public class Student {
    	@GeneratedValue
    	@Id
    	private Long student_id;
    	
    	@Column
    	private String name;
    	
    	@Column
    	private int age;
    }
    	public void testCreateNamedQuery(){
    		Query query = entityManager.createNamedQuery("testNamedQuery").setParameter(1, 3);
    		Student student = (Student) query.getSingleResult();
    	}
    8.1.3 createNativeQuery
    	public void testCreateNativeQuery(){
    		// 本地sql的意思是只能在数据库中执行的sql语句
    		String sql = "SELECT age FROM t_student WHERE student_id = ?";
    		Query query = entityManager.createNativeQuery(sql).setParameter(1, 18);
    		Object result = query.getSingleResult();
    	}

    8.2 关联查询

    存在一对多关系时,当我们查询一的一端时,默认多的一端是懒加载。此时我们如果想要一次性查询出所有的数据就需要使用关联查询

    注意: 下面 sql 中的重点就是要加上 fetch u.orders,表示要查询出用户所关联的所有订单

    	public void testLeftOuterJoinFetch(){
    		String jpql = "FROM t_users u LEFT OUTER JOIN FETCH u.orders WHERE u.id = ?";
    		
    		Users user = (Users) entityManager.createQuery(jpql).setParameter(1, 123).getSingleResult();
    	}

    The above is the detailed content of How to use SpringBoot JPA common annotations. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete