springboot使用jpa

springboot使用jpa

添加依赖

       <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>


    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.21</version>
    </dependency>

配置application.properties

spring.datasource.url=jdbc:mysql://localhost:13306/jpa
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop

spring.jpa.properties.hibernate.hbm2ddl.auto是hibernate的配置属性,其主要作用是:自动创建、更新、验证数据库表结构。该参数的几种配置如下:

  • create:每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。
  • create-drop:每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。
  • update:最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等应用第一次运行起来后才会。
  • validate:每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。

    创建实体

    @Entity
    public class User {

    public User(){

    }

    @Id
    @GeneratedValue
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private Integer age;

    // 省略构造函数

    // 省略getter和setter

    public Integer getAge() {
    return age;
    }

    创建访问接口

    public interface UserRepository extends JpaRepository

    User findByNameAndAge(String name, Integer age);

    @Query("from User u where u.name=:name")
    User findUser(@Param("name") String name);
    }

    功能测试

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class SpringbootJpaApplicationTests {

    @Autowired
    public UserRepository repository;

    @Test
    public void jpaTest() {
    repository.save(new User(11, "AA"));
    repository.save(new User(22, "BB"));
    repository.save(new User(33, "CC"));
    repository.save(new User(44, "DD"));
    repository.save(new User(55, "EE"));
    repository.save(new User(66, "FF"));
    //测试总数
    Assert.assertEquals(6, repository.findAll().size());
    //测试findByName
    Assert.assertEquals(66, repository.findByName("FF").getAge().intValue());
    Assert.assertEquals("EE", repository.findByNameAndAge("EE", 55).getName());
    Assert.assertEquals(44, repository.findUser("DD").getAge().intValue());
    repository.delete(repository.findByName("CC"));
    Assert.assertEquals(5, repository.findAll().size());

    }

    @Test
    public void contextLoads() {
    }

    }

猜你喜欢

转载自www.cnblogs.com/binfoo/p/9085294.html