接手了一个数据表比较多的项目,打算从原来的Mybatis转到hibernate,今日从jpa开始一步步探索
1.首先是包引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
2.配置文件,主要是两部分,一部分是数据库的链接还有一部分是hibernate的配置,数据库就不贴了,到处都有
#----------------------JPA------------------------------
spring.jpa.database = MYSQL
spring.jpa.show-sql = true
# (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = create
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.DefaultNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
3.创建一个实体
package com.Entity;
import lombok.Data;
import javax.persistence.*;
@Data
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue
private Long id;
private String name;
}
4.此时数据库中是没有任何表的,当我们启动springboot后表会自动创建,如下图,执行了sql
5.其次,我们需要创建一个UserRepository来继承Jpa原有的方法
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends
JpaRepository<User,Integer>, JpaSpecificationExecutor<User> {
}
6.之后便可运用UserRepository中的方法对User表进行各种操作了,这里插入一个记录
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserRepository UserRepository;
public void Insert() {
User aa=new User();
aa.setName("aaa");
UserRepository.save(aa);
}
}
我们用URL测试下
import com.Entity.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class text {
@Autowired
UserService userService;
@RequestMapping("/aa")
public void text(){
userService.Insert();
}
}
7.请求了一次/aa,结果如下
后续会慢慢一步步从jpa到hibernate的学习记录的,如果有什么不正确的,请各位大佬指正下。