本文转载自微信公众号「小明菜市场」,作者+小明菜市场。转载本文请联系小明菜市场公众号。
数据准备
数据库使用的数据表设计如下
建表语句如下
- SET NAMES utf8mb4;
- SET FOREIGN_KEY_CHECKS = 0;
- -- ----------------------------
- -- Table structure for t_user
- -- ----------------------------
- DROP TABLE IF EXISTS `t_user`;
- CREATE TABLE `t_user` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `user_name` varchar(255) DEFAULT NULL,
- `password` varchar(255) DEFAULT NULL,
- `last_login_time` datetime DEFAULT NULL,
- `sex` tinyint(4) DEFAULT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=armscii8;
- -- ----------------------------
- -- Records of t_user
- -- ----------------------------
- BEGIN;
- INSERT INTO `t_user` VALUES (1, 'json', '123', '2019-07-27 16:01:21', 1);
- INSERT INTO `t_user` VALUES (2, 'jack jo', '123', '2019-07-24 16:01:37', 1);
- INSERT INTO `t_user` VALUES (3, 'manistal', '123', '2019-07-24 16:01:37', 1);
- INSERT INTO `t_user` VALUES (4, 'landengdeng', '123', '2019-07-24 16:01:37', 1);
- INSERT INTO `t_user` VALUES (5, 'max', '123', '2019-07-24 16:01:37', 1);
- COMMIT;
- SET FOREIGN_KEY_CHECKS = 1;
新建 Spring Boot 工程
选择 File -> New -> Project 选择 Spring Initializr,选择 next 填写包名,项目名,选择下一步。选择依赖,Spring web starter 前面打钩,sql 选项为 Spring Data Jpa,MySql 项目名任意
引入 Pom配置
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-jpa</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-webflux</artifactId>
- </dependency>
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <scope>runtime</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>io.projectreactor</groupId>
- <artifactId>reactor-test</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
编写配置文件 application.yml
- server:
- port: 8086
- spring:
- #通用的数据源配置
- datasource:
- driverClassName: com.mysql.jdbc.Driver
- url: jdbc:mysql://localhost:3306/demo_test?useSSL=false&useUnicode=true&characterEncoding=utf8
- username: root
- password: 123
- jpa:
- #这个参数是在建表的时候,将默认的存储引擎切换为 InnoDB 用的
- database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
- #配置在日志中打印出执行的 SQL 语句信息。
- show-sql: true
- hibernate:
- #配置指明在程序启动的时候要删除并且创建实体类对应的表
- ddl-auto: create
编写示例代码
新建实体对象 UserDao.java
实体类,需要使用 @Entity 注解标注 需要对实体类的属性进行标注,使用 @Id 标注组件 使用 @Column 标注非主键
- /**
- * 用户实体类
- * */
- @Entity
- @Table(name="t_user")
- public class UserDO {
- @Id
- private Integer id;
- @Column(name="user_name",length = 200)
- private String userName;
- @Column(name="password",length = 200)
- private String password;
- @Column(name="sex")
- private Integer sex;
- @Column(name="last_login_time")
- private Date lastLoginTime;
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getUserName() {
- return userName;
- }
- public void setUserName(String userName) {
- this.userName = userName;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public Integer getSex() {
- return sex;
- }
- public void setSex(Integer sex) {
- this.sex = sex;
- }
- public Date getLastLoginTime() {
- return lastLoginTime;
- }
- public void setLastLoginTime(Date lastLoginTime) {
- this.lastLoginTime = lastLoginTime;
- }
- }
新建仓库接口类 UserRepository
仓库接口类,UserRepository 是我们常用的 Dao 接口,需要注意
- 使用 @Repository 注解
- 继承 JPARepository
- UserRepository 不需要编写任何代码,即可实现增删查改
- @Repository
- public interface UserRepository extends JPARepository<UserDO,Integer> {
- }
编写测试用例
在
- src/test/java/com/fishpro/jpa/
下,新增加
- UserRepositoryTest.java
使用
- @RunWith(SpringRunner.class)
和
- @SpringBootTest
注解标注类。
- @RunWith(SpringRunner.class)
- @SpringBootTest
- public class UserRepositoryTest{
- }
新增加用户数据
- /**
- * 初始化一个对象 UserDO 测试Insert过程
- * */
- @Before
- public void before(){
- UserDO userDO=new UserDO();
- userDO.setId(1);
- userDO.setUserName("fishpro");
- userDO.setSex(1);
- userDO.setLastLoginTime(new Date());
- userDO.setPassword("passWord");
- userRepository.save(userDO);
- }
查询单个用户数据
- @Test
- public void testFind(){
- Optional<UserDO> optionalUserDO=userRepository.findById(1);
- if(optionalUserDO.isPresent()){
- UserDO userDO=optionalUserDO.get();
- System.out.println("testFind user"+userDO.getUserName());
- }
- }
查询多个数据
- @Test
- public void testFindAll(){
- List<UserDO> list=userRepository.findAll();
- for (UserDO user:list
- ) {
- System.out.println("user_name:"+user.getUserName());
- }
- }
更新数据
- @Test
- public void testUpdate(){
- Optional<UserDO> optionalUserDO=userRepository.findById(1);
- if(optionalUserDO.isPresent()){
- UserDO userDO=optionalUserDO.get();
- userDO.setUserName("fishpro001");
- userRepository.save(userDO);
- System.out.println("testFind user"+userDO.getUserName());
- }
- }
删除数据
- @After
- public void after(){
- userRepository.deleteById(1);
- userRepository.deleteById(2);
- userRepository.deleteById(3);
- }
联合主键
例如定义表中userId,roleId 都是主键,此时这样设置
1.定义一个主键类
- public class UserRoleKey implements Serializable {
- private Integer userId;
- private Integer roleId;
- }
2.定义实体类
- @Entity
- @Table(name="t_user_role")
- @IdClass(UserRoleKey.class) //注意这里是引入了 定义的符合主键类
- public class UserRoleDO {
- @Id
- private Integer userId;
- @Id
- private Integer roleId;
- public Integer getUserId() {
- return userId;
- }
- public void setUserId(Integer userId) {
- this.userId = userId;
- }
- public Integer getRoleId() {
- return roleId;
- }
- public void setRoleId(Integer roleId) {
- this.roleId = roleId;
- }
- }