spring-data-jpa使用总结

1.pom.xml配置

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-jpa</artifactId>
  4. </dependency>

2.application.yml配置

  1. spring:
  2. application:
  3. name: test
  4. datasource:
  5. url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
  6. driver-class-name: com.mysql.jdbc.Driver
  7. username: root
  8. password: root
  9. jpa:
  10. show-sql: true
  11. database-platform: org.hibernate.dialect.MySQL5InnoDBDialect

3.实体定义

  1. @Entity
  2. @Table(name="tb_user")
  3. @Data
  4. public class User implements Serializable {
  5. @Id
  6. @GeneratedValue(generator = "IdUtil")
  7. @GenericGenerator(name = "IdUtil", strategy = "com.jia.test.jpa.beans.common.IdUtil")
  8. private String id;
  9. private String username;
  10. private String email;
  11. private String phone;
  12. private Date birthday;
  13. private Date create_time;
  14. private Date update_time;
  15. }

3.1 表主键生成策略自定义

  1. public class IdUtil implements IdentifierGenerator {
  2. @Override
  3. public Serializable generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object o) throws HibernateException {
  4. return getId() + "";
  5. }
  6. private Serializable getId() {
  7. return 1;
  8. }
  9. }

4.mapper引用

  1. @Repository
  2. public interface TestUserMapper extends JpaRepository<User,Long>, JpaSpecificationExecutor<Long> {
  3. }

5.使用方式

  1. @SpringBootTest(classes = TestJpaApplication.class)
  2. @RunWith(SpringRunner.class)
  3. public class Test1111 {
  4. @Autowired
  5. private TestUserMapper testUserMapper;
  6. @Test
  7. public void test() {
  8. User user = new User();
  9. user.setId("1");
  10. user.setUsername("张三");
  11. user.setBirthday(new Date());
  12. user.setEmail("");
  13. user.setCreate_time(new Date());
  14. user.setUpdate_time(new Date());
  15. User save = testUserMapper.save(user);
  16. if(save == null) {
  17. System.out.println("error");
  18. }
  19. System.out.println(save);
  20. }
  21. }