1.创建子模块
这里我们创建一个子模块
1 2
| group = 'com.ray.study' artifact ='spring-boot-05-jpa'
|
2.引入依赖
2.1 继承父工程依赖
在父工程spring-boot-seeds
的 settings.gradle
加入子工程
1 2 3 4 5 6
| rootProject.name = 'spring-boot-seeds' include 'spring-boot-01-helloworld' include 'spring-boot-02-restful-test' include 'spring-boot-03-thymeleaf' include 'spring-boot-04-swagger2' include 'spring-boot-05-jpa'
|
这样,子工程spring-boot-05-jpa
就会自动继承父工程中subprojects
`函数里声明的依赖,主要包含如下依赖:
1 2 3 4 5
| implementation 'org.springframework.boot:spring-boot-starter-web' testImplementation 'org.springframework.boot:spring-boot-starter-test'
compileOnly 'org.projectlombok:lombok' annotationProcessor 'org.projectlombok:lombok'
|
2.2 引入jpa
依赖
将子模块spring-boot-05-jpa
的build.gradle
修改为如下内容:
1 2 3 4 5 6 7
| dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'mysql:mysql-connector-java' }
|
3.修改配置
3.1 修改application.yml
主要配置下数据源与JPA
由于我们配置的ddl-auto = update
,因此不需要创建相关数据表,只需要创建integrate-jpa
数据库即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| server: port: 8088 servlet: context-path: /
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/integrate-jpa?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8 username: root password: root jpa: database: mysql show-sql: true hibernate: ddl-auto: update
|
数据源的配置类为DataSourceProperties
,具体的默认配置:
1 2 3 4 5 6
| public DataSourceBuilder<?> initializeDataSourceBuilder() { return DataSourceBuilder.create(getClassLoader()).type(getType()) .driverClassName(determineDriverClassName()).url(determineUrl()) .username(determineUsername()).password(determinePassword()); }
|
JPA的配置类为JpaProperties
、HibernateProperties
Hibernate DDL
配置的含义:
- create: 每次运行程序时,都会重新创建表,故而数据会丢失
- create-drop: 每次运行程序时会先创建表结构,然后待程序结束时清空表
- upadte: 每次运行程序,没有表时会创建表,如果对象发生改变会更新表结构,原有数据不会清空,只会更新(推荐使用)
- validate: 运行程序会校验数据与数据库的字段类型是否相同,字段不同会报错
4.业务实现
4.1 model
(1)BaseDO
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| package com.ray.study.springboot05jpa.model;
import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import lombok.NoArgsConstructor;
import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.MappedSuperclass; import java.util.Date;
@Data @NoArgsConstructor @MappedSuperclass public class BaseDO {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
@JsonIgnore private Date creationDate;
@JsonIgnore private Date lastUpdateDate; }
|
(2)User
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| package com.ray.study.springboot05jpa.model;
import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor;
import javax.persistence.Entity; import javax.persistence.Table;
@Data @NoArgsConstructor @AllArgsConstructor @Entity @Table(name = "user") public class User extends BaseDO{
private String name;
private Integer age;
}
|
4.2 repository
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| package com.ray.study.springboot05jpa.repository;
import com.ray.study.springboot05jpa.model.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository;
import java.util.List;
@Repository public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByAgeGreaterThanEqualOrderById(Integer age);
List<User> findAllByName(String name);
List<User> findByNameLike(String name);
List<User> findByNameContaining(String name); }
|
5.单元测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
| package com.ray.study.springboot05jpa.repository;
import com.ray.study.springboot05jpa.model.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList; import java.util.List; import java.util.Optional;
import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
@RunWith(SpringRunner.class) @SpringBootTest public class UserRepositoryTest {
@Autowired UserRepository userRepository;
@Test public void queryUser(){ List<User> userToAddList = new ArrayList<>(); userToAddList.add(new User("aatomcat000",20)); userToAddList.add(new User("tomcat",21)); userToAddList.add(new User("tttomcat",22)); userToAddList.add(new User("tttomcat111",23)); userToAddList.add(new User("tomcataaa",24));
userToAddList.forEach(user -> { userRepository.save(user); });
List<User> userList = userRepository.findAllByName("tom"); System.out.println(userList);
List<User> userList2 = userRepository.findByAgeGreaterThanEqualOrderById(21); System.out.println(userList2);
List<User> userList3 = userRepository.findByNameLike("tom"); System.out.println(userList3);
List<User> userList4 = userRepository.findByNameContaining("tom"); System.out.println(userList4); }
@Test public void insertUser(){
User user = new User(); user.setName("tom"); user.setAge(21); User user1 = userRepository.save(user);
assertThat(user.getId(),is(notNullValue())); }
@Test public void updateUser(){
User user = new User(); user.setId(1L); user.setName("tom2"); user.setAge(1212); User user1 = userRepository.save(user);
Optional<User> optionalUser = userRepository.findById(1L); User updatedUser = null; if(optionalUser.isPresent()){ updatedUser = optionalUser.get(); }
assertThat(updatedUser.getAge(),is(1212)); }
@Test public void deleteUser(){ User user = new User(); user.setName("tom2"); userRepository.delete(user);
List<User> userList = userRepository.findAllByName("tom2"); assertThat(userList, is(nullValue()));
}
}
|