springboot整合jpa项目入门级别demo
前言
一、新建一个空boot项目
二、准备好数据库,下面以MySQL为主
- 创建好测试表dog表,待用
三、导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.14</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
四、生成JPA实体
JPA自动生成 JPA 实体类(idea).
五、JPA基本注解
- @entity
- @Table(name=“table_name”)
当前实体与其映射的数据库表名不同时需要加此注解,如果一致,不加也行 - @Id 主键
- @GeneratedValue
主键的生成策略,例:@GeneratedValue(strategy = GenerationType.AUTO) - @Basic
表示一个简单的属性到数据库表的字段的映射,对于没有任何标注的getXXX()方法,默认即为@basic,会把XXX映射为数据库的一列 即:如果在实体的get方法上没加注解,则默认加了@Basic(此注解加不加都行) - @Column(name = “dog_name”) 映射数据库字段名
- @Transient 表示该属性并非一个到数据库表的字段的映射,ORM框架将忽略该属性,如果一个属性并非数据库表的字段的映射,就务必将其标示为@Transient,否则,ORM框架默认其注解为@basic
- @Temporal(TemporalType.DATE)
在进行属性映射时可使用此注解来调整数据库存储日期的精度(通过设置:TemporalType.DATE,TemporalType.TIMESTAMP)
六、JPQL 和 EntityManager
package com.liu.susu.pojo;
import javax.persistence.*;
import java.util.Objects;
@NamedQuery(name = "testNamedQuery",query = "select d from com.liu.susu.pojo.Dog d")
@Entity
public class Dog {
private int dogNum;
private String dogName;
private String dogKind;
private Integer dogAge;
private String decision;
public Dog(){
}
public Dog(int dogNum, String dogName) {
this.dogNum = dogNum;
this.dogName = dogName;
}
@Id
@Column(name = "dog_num")
public int getDogNum() {
return dogNum;
}
public void setDogNum(int dogNum) {
this.dogNum = dogNum;
}
@Basic
@Column(name = "dog_name")
public String getDogName() {
return dogName;
}
public void setDogName(String dogName) {
this.dogName = dogName;
}
@Basic
@Column(name = "dog_kind")
public String getDogKind() {
return dogKind;
}
public void setDogKind(String dogKind) {
this.dogKind = dogKind;
}
@Basic
@Column(name = "dog_age")
public Integer getDogAge() {
return dogAge;
}
public void setDogAge(Integer dogAge) {
this.dogAge = dogAge;
}
@Basic
@Column(name = "decision")
public String getDecision() {
return decision;
}
public void setDecision(String decision) {
this.decision = decision;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Dog dog = (Dog) o;
return dogNum == dog.dogNum && Objects.equals(dogName, dog.dogName) && Objects.equals(dogKind, dog.dogKind) && Objects.equals(dogAge, dog.dogAge) && Objects.equals(decision, dog.decision);
}
@Override
public int hashCode() {
return Objects.hash(dogNum, dogName, dogKind, dogAge, decision);
}
}
package com.liu.susu.dao;
import com.liu.susu.pojo.Dog;
import org.springframework.data.jpa.repository.JpaRepository;
public interface DogDao extends JpaRepository<Dog,Integer> {
}
package com.liu.susu.dao;
import com.liu.susu.pojo.Dog;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface DogDao2 extends JpaRepository<Dog,Integer> {
@Query(value = "from com.liu.susu.pojo.Dog")
List<Dog> getDogList();
@Query(value = "select d from com.liu.susu.pojo.Dog d")
List<Dog> getDogList2();
@Query(value = "select dogNum,dogName from com.liu.susu.pojo.Dog d")
List<Object[]> getDogObjectList();
@Query(value = "select new com.liu.susu.pojo.Dog(dogNum,dogName) from com.liu.susu.pojo.Dog d")
List<Dog> getDogList3();
@Query(value = "select d from com.liu.susu.pojo.Dog d where d.dogAge=?1")
List<Dog> getDogList0(int dogAge);
}
package com.liu.susu.controller;
import com.alibaba.fastjson.JSONObject;
import com.liu.susu.dao.DogDao;
import com.liu.susu.pojo.Dog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
@RequestMapping("/dog/dao1")
public class DogDaoController {
@Autowired
private DogDao dogDao;
@ResponseBody
@RequestMapping("/all")
public String testFindAll(){
List<Dog> dogList = dogDao.findAll();
return JSONObject.toJSONString(dogList);
}
@ResponseBody
@RequestMapping("/all2")
public List<Dog> testFindAll2(){
List<Dog> dogList = dogDao.findAll(Sort.by("dogAge").descending());
return dogList;
}
@ResponseBody
@RequestMapping("/save")
public List<Dog> testSave(){
Dog dog = new Dog();
dog.setDogNum(1005);
dog.setDogName("酥妮");
dog.setDogAge(1);
dogDao.save(dog);
List<Dog> dogList = dogDao.findAll();
return dogList;
}
}
package com.liu.susu.controller;
import com.liu.susu.dao.DogDao2;
import com.liu.susu.pojo.Dog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
@RequestMapping("/dog/dao2")
public class DogDao2Controller {
@Autowired
private DogDao2 dogDao2;
@ResponseBody
@RequestMapping("/list")
private List<Dog> getDogList(){
List<Dog> dogList = dogDao2.getDogList();
return dogList;
}
@ResponseBody
@RequestMapping("/list2")
private List<Dog> getDogList2(){
List<Dog> dogList = dogDao2.getDogList2();
return dogList;
}
@ResponseBody
@RequestMapping("/objList")
private List<Object[]> getDogObjectList(){
List<Object[]> dogObjectList = dogDao2.getDogObjectList();
return dogObjectList;
}
@ResponseBody
@RequestMapping("/list3")
private List<Dog> getDogList3(){
List<Dog> dogList = dogDao2.getDogList3();
return dogList;
}
@ResponseBody
@RequestMapping("/listByDogAge")
private List<Dog> getDogListByParam(@RequestParam int dogAge){
List<Dog> dogList = dogDao2.getDogList0(dogAge);
return dogList;
}
}
package com.liu.susu.controller;
import com.liu.susu.pojo.Dog;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;
import java.util.List;
@Controller
@RequestMapping("/dog/entityManager1")
public class EntityManagerController {
@PersistenceContext
private EntityManager entityManager;
@ResponseBody
@RequestMapping("/list1")
public List<Dog> getDogList(){
String sql = "select * from dog";
List<Dog> dogList = entityManager.createNativeQuery(sql)
.getResultList();
return dogList;
}
@ResponseBody
@RequestMapping("/list2")
public List<Dog> getDogList2(){
String sql = "select * from dog";
List<Dog> dogList = entityManager.createNativeQuery(sql,Dog.class)
.getResultList();
return dogList;
}
@ResponseBody
@RequestMapping("/dog1")
public Dog getDogByNum(@RequestParam Integer dogNum){
String sql = "select * from dog d where d.dog_num=?1";
Query query = entityManager.createNativeQuery(sql,Dog.class);
query.setParameter(1,dogNum);
Dog dog = (Dog) query.getSingleResult();
return dog;
}
@ResponseBody
@RequestMapping("/save")
@Transactional()
public String testPersist(){
Dog dog = new Dog();
dog.setDogNum(1006);
dog.setDogName("测试");
dog.setDogAge(0);
entityManager.persist(dog);
return "ok";
}
@ResponseBody
@RequestMapping("/merge")
@Transactional()
public String testMerge(){
Dog dog = new Dog();
dog.setDogNum(1006);
dog.setDogName("测试2");
dog.setDogAge(0);
entityManager.merge(dog);
return "ok";
}
}
package com.liu.susu.controller;
import com.liu.susu.pojo.Dog;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
@Controller
@RequestMapping("/dog/jpqlAndEntityManager")
public class JpqlAndEntityManagerController {
@PersistenceContext
private EntityManager entityManager;
@ResponseBody
@RequestMapping("/list1")
public List<Dog> getDogList(){
List<Dog> dogList = entityManager.createNamedQuery("testNamedQuery")
.getResultList();
return dogList;
}
}
七、配置文件
server.port=8993
# 应用名称
spring.application.name=springboot-jpa
# 数据库驱动:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据库连接地址
spring.datasource.url=jdbc:mysql://localhost:3306/liu?serverTimezone=UTC
# 数据库用户名&密码:
spring.datasource.username=root
spring.datasource.password=root
#spring.jpa.generate-ddl=true
#spring.jpa.hibernate.ddl-auto=validate
spring.jpa.show-sql=true
# 指定数据库得类型
spring.jpa.database-platform=org.hibernate.dialect.MySQL57InnoDBDialect
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.liu.susu</groupId>
<artifactId>springboot-jpa</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-jpa</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.3.2.RELEASE</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--本demo 核心依赖 begin-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.14</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
<!--本demo 核心依赖 end-->
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.3.7.RELEASE</version>
<configuration>
<mainClass>com.liu.susu.SpringbootJpaApplication</mainClass>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
八、demo包
spring boot整合JPA——demo
|