本文共 2886 字,大约阅读时间需要 9 分钟。
工程配置,添加maven的依赖,jpa的依赖有如下,简单的就是一个jpa和mysql:
org.springframework.boot spring-boot-starter-data-jpa mysql mysql-connector-java
在application.properties中添加数据库的链接信息
spring.datasource.url=jdbc:mysql://localhost:3306/jpa?useSSL=falsespring.datasource.username=rootspring.datasource.password=123456spring.datasource.driver-class-name=com.mysql.jdbc.Driver
其中,
useSSL=false 表示跳过ssl的验证,不需要关心
还可以添加一个属性:
spring.jpa.properties.hibernate.hbm2ddl.auto=create
spring.jpa.properties.hibernate.hbm2ddl.auto是hibernate的配置属性,其主要作用是:自动创建、更新、验证数据库表结构。该参数的几种配置如下:
create
:每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。create-drop
:每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。就是说当你使用完之后 你在数据库中是看不到这张表的update
:最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等应用第一次运行起来后才会。validate
:每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值引入配置完成之后,开始构建代码侧
实体类:
/** * Created by sunzhitao on 2018/4/2. */@Entitypublic class User { @Id @GeneratedValue private Long id; @Column(nullable = false) private String name; @Column(nullable = false) private Integer age;//省略getter setter 构造函数}
下面针对User实体创建对应的Repository
接口实现对该实体的数据访问,如下代码:
public interface UserRepository extends JpaRepository{ User findByName(String name); User findByNameAndAge(String name,Integer age); @Query("from User u where u.name=:name") User findUser(@Param("name") String name);}
使用了Spring-data-jpa,只需要编写类似上面这样的接口就可实现数据访问。不需要再自己编写接口实现类。
UserRepository接口继承自JpaRepository,通过查看JpaRepository
接口的,可以看到该接口本身已经实现了创建(save)、更新(save)、删除(delete)、查询(findAll、findOne)等基本操作的函数,因此对于这些基础操作的数据访问就不需要开发者再自己定义。
开发中,JpaRepository
接口定义的接口还不够,有些需要自定义的查询或者删除修改等操作。Jpa还给我们增加了一种通过约定方法名称达到效果的功能。比如:
User findByNameAndAge(String name,Integer age);
通过名字和年龄查询用户信息。还有一种通过JPQL语句查询,
@Query("from User u where u.name=:name") User findUser(@Param("name") String name);
通过使用 注解来创建查询,类似 :name 映射@param 指定的参数
单元测试:
@RunWith(SpringRunner.class)@SpringBootTestpublic class SpringbootJpaApplicationTests { @Autowired private UserRepository userRepository; @Test public void contextLoads() { userRepository.save(new User("sunny",18)); userRepository.save(new User("susan",12)); userRepository.save(new User("sunshine",20)); User u = userRepository.findByName("susan"); System.out.println("u:"+u.toString()); }}
另外,当springboot启动完成之后 如果运行完就结束了 可以添加一个 System.in.read(); 比如:
@SpringBootApplicationpublic class SpringbootJpaApplication { public static void main(String[] args) throws IOException { SpringApplication.run(SpringbootJpaApplication.class, args); System.in.read(); }}
转载地址:http://gfjxi.baihongyu.com/