Spring Data JPA应用:笔记

1、@Transient和@Jsonlgnore注解的使用

2、Spring Data JPA中使用延时加载时控制Session的生命周期

3、使用@Column(nullable = false) 和 @Column(unique=true)注解

1、@Transient和@Jsonlgnore注解的使用

@Transient注解:表示该属性并非一个数据库表的字段的映射,ORM框架将忽略该属性。如果一个属性并非数据库表的字段映射,就务必将其标示为@Transient,即它是不持久的,为虚拟字段。

@Jsonlgnore注解:作用是JSON序列化时将Java Bean中的一些属性忽略掉,序列化和反序列化都受影响。

2、Spring Data JPA中使用延时加载时控制Session的生命周期

在Spring Data JPA中在使用延时加载时,要控制Session的生命周期,否则会出现“could not initialize proxy [xxxxxx#1] - no Session”错误。可以在配置文件中配置以下代码来控制Session的生命周期:

application.properties配置文件:

spring.jpa.open-in-view=true
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true

application.yml配置文件:

3、使用@Column(nullable = false) 和 @Column(unique=true)注解

unique=true:是指这个字段的值在这张表里不能重复,所有记录值都要唯一,就像主键那样。

nullable=false:是这个字段在保存时必需有值,不能还是null值就调用save去保存入库。

例如:

package com.example.myapp.domain;

import java.io.Serializable;
import javax.persistence.*;

@Entity
public class User implements Serializable {

	@Id
	@GeneratedValue
	private Long id;

	//账号,必须唯一
	@Column(unique = true)
	private String account;

	//姓名,不能为空
	@Column(nullable = false)
	private String name;


	// 忽略其他代码...
}
发布了377 篇原创文章 · 获赞 278 · 访问量 180万+

猜你喜欢

转载自blog.csdn.net/pan_junbiao/article/details/105239144