美文网首页
Spring Boot整合Spring Data JPA

Spring Boot整合Spring Data JPA

作者: AlienPaul | 来源:发表于2017-11-15 15:33 被阅读0次

    新建Spring Boot空项目

    打开Intellij IDEA,选择File -> New -> New Project -> 左侧的Spring Initializr。按照向导的提示进行操作,当遇到依赖包选择页面时候,勾选JPA和MySQL。如下图所示:


    image.png

    配置数据库连接:

    在application.properties文件中写入以下内容:

    # driver 类名
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    # 数据库用户名
    spring.datasource.username=root
    # 数据库密码
    spring.datasource.password=123456
    # 数据库连接URL
    spring.datasource.url=jdbc:mysql://localhost:3306/demo
    # 数据库表生成策略,create表示会自动创建表,并且会破坏之前的数据
    spring.jpa.hibernate.ddl-auto=create
    

    编写实体类

    // @Entity注解声明该类为实体类
    @Entity
    public class Student implements Serializable {
        // @Id此字段为主键字段
        // @GeneratedValue 主键的生成策略,此处采用主键自增
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private long id;
    
        private String name;
    
        public long getId() {
            return id;
        }
    
        public void setId(long id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
    
            Student student = (Student) o;
    
            if (id != student.id) return false;
            return name != null ? name.equals(student.name) : student.name == null;
        }
    
        @Override
        public int hashCode() {
            int result = (int) (id ^ (id >>> 32));
            result = 31 * result + (name != null ? name.hashCode() : 0);
            return result;
        }
    }
    

    编写Repository

    @Service
    public interface StudentRepo extends JpaRepository<Student, Long> {
        List<Student> findByName(String name);
    }
    

    注意:

    • 该接口继承了JpaRepository接口。泛型的写法为<实体类型,主键类型>。
    • JpaRepository接口继承了PagingAndSortingRepository和CrudRepository。顾名思义它们分别提供了分页排序查找以及基本的CRUD功能。

    编写测试类

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class DemoApplicationTests {
    
        // 注入Repository
        @Autowired
        private StudentRepo studentRepo;
    
        @Test
        public void contextLoads() {
    
            Student student = new Student();
            student.setName("Paul");
    
            // 调用CRUDRepository接口中的save方法保存数据
            studentRepo.save(student);
            // 按照name字段查找数据
            student = studentRepo.findByName("Paul").get(0);
        }
    }
    

    相关文章

      网友评论

          本文标题:Spring Boot整合Spring Data JPA

          本文链接:https://www.haomeiwen.com/subject/ecacvxtx.html