SpringBoot 整合 SpringDataJPA

SpringBoot 整合 SpringDataJPA的步骤

  • 在SpringBoot项目的pom.xml文件中引入依赖
<!-- MySQL 连接驱动依赖 -->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Spring Boot JPA 依赖 -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
  • 在application.properties配置文件中配置SpringDataJPA
########################################################
###	配置数据源
########################################################
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/***
spring.datasource.username = ***
spring.datasource.password = ***
########################################################
###	解决乱码问题
########################################################
spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
server.tomcat.uri-encoding=UTF-8
########################################################
###	Spring Data JPA配置
########################################################
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
###	运行时输出jpa执行的sql语句
spring.jpa.show-sql=true
### spring-boot-starter-data-jpa自动映射创建表动作 配置: 有表更新,无表创建
spring.jpa.hibernate.ddl-auto=update
  • 在src/main/java目录下的entity包中创建实体类
    例:在entity包中创建一个实体类
    说明:entity包要和SpringBoot启动类同级
    table的字段和entity的属性对应方式:student_id对应studentId
import java.util.Date;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.springframework.format.annotation.DateTimeFormat;

@Entity
@Table(name="student")//数据库的表名,如果数据库中没有此表,可自动生成
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" })//标不需要转化为json的属性 
public class Student implements Serializable{
	private static final long serialVersionUID = 1L;
	@Id //实体类的主键
	@GeneratedValue(strategy = GenerationType.IDENTITY) //自动增长列
	private Integer studentId;
	private String studentName;
	private Integer studentAge; 
	@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")	//格式化日期类型
	private Date studentBirthday; //学生出生年月
	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Student(Integer studentId, String studentName, Integer studentAge, Date studentBirthday) {
		super();
		this.studentId = studentId;
		this.studentName = studentName;
		this.studentAge = studentAge;
		this.studentBirthday = studentBirthday;
	}
	public Integer getStudentId() {
		return studentId;
	}
	public void setStudentId(Integer studentId) {
		this.studentId = studentId;
	}
	public String getStudentName() {
		return studentName;
	}
	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}
	public Integer getStudentAge() {
		return studentAge;
	}
	public void setStudentAge(Integer studentAge) {
		this.studentAge = studentAge;
	}
	public Date getStudentBirthday() {
		return studentBirthday;
	}
	public void setStudentBirthday(Date studentBirthday) {
		this.studentBirthday = studentBirthday;
	}
	@Override
	public String toString() {
		return "Student [studentId=" + studentId + ", studentName=" + studentName + ", studentAge=" + studentAge
				+ ", studentBirthday=" + studentBirthday + "]";
	}
}
  • 在repository包下创建Repository接口,并继承 JpaRepository接口
    例:在repository包中创建一个StudentRepository接口
    说明:repository包要和SpringBoot启动类同级,repository层即dao层
import org.springframework.data.jpa.repository.JpaRepository;

import com.rx.entity.Student;

/**
 * JpaRepository<T, ID>中的T:实体类的类型、ID:主键的数据类型
 *
 */
public interface StudentRepository extends JpaRepository<Student, Integer>{

}
  • 在controller包下创建Controller类
    例:在controller包中创建一个StudentController接口
    说明:entity包要和SpringBoot启动类同级
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ysd.entity.Student;
import com.ysd.repository.StudentRepository;

@RestController
public class StudentController {
	
	//自动注入StudentRepository接口 
	@Autowired
	private StudentRepository repository;
	
	@RequestMapping("/insert")
	public Object insert(Student student) {
		// 调用StudentRepository中默认的的save方法
		student = repository.save(student);
		return student;
	}

}
  • 在SpringBoot启动类上添加@EnableJpaRepositories注解
    说明:@EnableJpaRepositories:注解用于 Srping Data JPA 的代码配置,用于取代 xml 形式的配置文件
    例:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@EnableJpaRepositories
@SpringBootApplication
public class App {
	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}
}
  • 启动项目测试
    在浏览器中访问:http://localhost:8080/insert?studentName=小明&studentAge=18&studentBirthday=2000-08-13 11:21:30

实体类中常用的注解

  • @Entity:标记在类名上面,作为实体类的标识
  • @Table:当实体类与其映射的数据库表名不相同时需要使用 @Table注解 说明,该注解与 @Entity注解 并列使用,置于实体类声明语句之前,可写于单独语句行,也可与声明语句同行。 @Table注解 的常用选项是 name,用于指明数据库的表名。 @Table注解 还有一个两个选项 catalog 和 schema 用于设置表所属的数据库目录或模式,通常为数据库名。uniqueConstraints 选项用于设置约束条件,通常不须设置
  • @Id:设置对象表示符,标识的实体类的属性映射对应表中的主键
  • @GeneratedValue:设置标识符的生成策略,常与 @Id注解 一起使用。参数:strategy 指定具体的生成策略
    方式一:@GeneratedValue(strategy=GenerationType.AUTO) 也是默认策略, 即写成@GeneratedValue 也可;类似 Hibernate 的 native 策略,生成方式取决于底层的数据库
    方式二:
    @GeneratedValue(strategy = GenerationType.IDENTITY)指定 自动增长 策略,适用于 MySQL
    方式三:
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = “seqtblperson”)指定 序列 策略,常用于 Oracle,其中 generator 表示生成器的名字。而且还要指定@SequenceGenerator(name =
    “seqtblperson”, sequenceName = “seqtblperson”, allocationSize = 1)注解配合使用。其中 name 指定生成器的名字(与 generator 的值一样),sequenceName 指定数据库中定义序列的名字,allocationSize 指定序列每次增长 1
  • @Column:描述数据库表中该字段的定义,具有以下属性:
    name:表示数据库表中该字段的名称,默认情形属性名称一致
    nullable:表示该字段是否允许为 null,默认为 true
    unique:表示该字段是否是唯一标识,默认为 false
    length:表示该字段的大小,仅对 String类型 的字段有效
    insertable:表示在 ORM 框架执行插入操作时,该字段是否应出现 INSETRT 语句中,默认为 true
    updateable:表示在 ORM 框架执行更新操作时,该字段是否应该出现在 UPDATE 语句中,默认为 true
    columnDefinition:表示该字段在数据库中的实际类型。通常 ORM 框架可以根据属性类型自动判断数据库中字段的类型,但是对于 Date 类型仍无法确定数据库中字段类型究竟是 DATE,TIME 还是
    TIMESTAMP
  • @OrderBy:在加载数据的时候可以为其指定顺序
  • @Transient:表示该属性并非一个到数据库表的字段的映射,ORM 框架将忽略该属性。如果一个属性并非数据库表的字段映射。就务必将其标示为@Transient。否则,ORM 框架默认其注解为@Basic
发布了22 篇原创文章 · 获赞 0 · 访问量 2769

猜你喜欢

转载自blog.csdn.net/Xu_Ren/article/details/105112444
今日推荐