Spring Boot 集成 JPA 的步骤

配置依赖

compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '1.5.2.RELEASE'
compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.41'

编写配置文件

1、JPA 的配置

@EnableJpaRepositories(basePackages = "com.liwei.dao")
@EntityScan(basePackages = "com.liwei.entity")
public class JpaConfig {
}

2、数据库连接的配置和其它配置

spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/spring-boot-security?useUnicode=true&characterEncoding=UTF-8
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto=update

创建数据库的 SQL 语句:

CREATE DATABASE `spring-boot-security` DEFAULT CHARSET utf8 COLLATE utf8_general_ci;

编写 dao 层和 entity 的代码

public interface UserRepository extends JpaRepository<User, Long> {
User findByUserName(String userName);
}
public interface UserRolesRepository extends JpaRepository<UserRole,Long> {

}
@Table(name = "t_user")
@Entity
public class User { private Long userId;
private String userName;
private String password;
private String email;
private int enabled; @Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id")
public Long getUserId() {
return userId;
} public void setUserId(Long userId) {
this.userId = userId;
} @Column(name = "user_name")
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 String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} public int getEnabled() {
return enabled;
} public void setEnabled(int enabled) {
this.enabled = enabled;
} public User() {
} public User(Long userId, String userName, String password, String email, int enabled) {
this.userId = userId;
this.userName = userName;
this.password = password;
this.email = email;
this.enabled = enabled;
} @Override
public String toString() {
return "User{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
", email='" + email + '\'' +
", enabled=" + enabled +
'}';
}
}
@Table(name = "t_user_roles")
@Entity
public class UserRole { private Long userRoleId; private Long userId; private String role; @Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_role_id")
public Long getUserRoleId() {
return userRoleId;
} public void setUserRoleId(Long userRoleId) {
this.userRoleId = userRoleId;
} @Column(name = "user_id")
public Long getUserId() {
return userId;
} public void setUserId(Long userId) {
this.userId = userId;
} public String getRole() {
return role;
} public void setRole(String role) {
this.role = role;
}
}

为了便于测试,我们还编写了服务层的方法:

public interface IUserService {

    User findByUserName(String userName);
}
@Service
public class UserServiceImpl implements IUserService { @Autowired
private UserRepository userRepository; @Override
public User findByUserName(String userName) {
return userRepository.findByUserName(userName);
}
}

编写测试代码

testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '1.5.2.RELEASE'
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringBootSecurityApplication.class)
public class IUserServiceTest { @Autowired
private IUserService userService;
@Autowired
private UserRepository userRepository; @Test
public void initData() throws Exception {
User user = new User();
user.setUserName("liwei");
user.setPassword("123456");
user.setEmail("121088825");
user.setEnabled(1);
User user1 = userRepository.save(user);
System.out.println(user1);
} @Test
public void findByUserName() throws Exception {
User user = userService.findByUserName("liwei");
System.out.println(user); } }

Spring Boot 集成 JPA 的步骤的更多相关文章

  1. Spring Boot集成JPA的Column注解命名字段无效的问题

    偶然发现,Spring Boot集成jpa编写实体类的时候,默认使用的命名策略是下划线分隔的字段命名. Spring Boot版本:1.5.4.release 数据表: id int, userNam ...

  2. spring boot 集成 Mybatis,JPA

    相对应MyBatis, JPA可能大家会比较陌生,它并不是一个框架,而是一组规范,其使用跟Hibernate 差不多,原理层面的东西就不多讲了,主要的是应用. Mybatis就不多说了,SSM这三个框 ...

  3. MyBatis初级实战之一:Spring Boot集成

    欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...

  4. 【实验一 】Spring Boot 集成 hibernate & JPA

    转眼间,2018年的十二分之一都快过完了,忙于各类事情,博客也都快一个月没更新了.今天我们继续来学习Springboot对象持久化. 首先JPA是Java持久化API,定义了一系列对象持久化的标准,而 ...

  5. (37)Spring Boot集成EHCache实现缓存机制【从零开始学Spring Boot】

    [本文章是否对你有用以及是否有好的建议,请留言] 写后感:博主写这么一系列文章也不容易啊,请评论支持下. 如果看过我之前(35)的文章这一篇的文章就会很简单,没有什么挑战性了. 那么我们先说说这一篇文 ...

  6. (35)Spring Boot集成Redis实现缓存机制【从零开始学Spring Boot】

    [本文章是否对你有用以及是否有好的建议,请留言] 本文章牵涉到的技术点比较多:Spring Data JPA.Redis.Spring MVC,Spirng Cache,所以在看这篇文章的时候,需要对 ...

  7. Spring Boot 集成 FreeMarker 详解案例(十五)

    一.Springboot 那些事 SpringBoot 很方便的集成 FreeMarker ,DAO 数据库操作层依旧用的是 Mybatis,本文将会一步一步到来如何集成 FreeMarker 以及配 ...

  8. 【spring boot】14.spring boot集成mybatis,注解方式OR映射文件方式AND pagehelper分页插件【Mybatis】pagehelper分页插件分页查询无效解决方法

    spring boot集成mybatis,集成使用mybatis拖沓了好久,今天终于可以补起来了. 本篇源码中,同时使用了Spring data JPA 和 Mybatis两种方式. 在使用的过程中一 ...

  9. Spring Boot集成Spring Data Reids和Spring Session实现Session共享

    首先,需要先集成Redis的支持,参考:http://www.cnblogs.com/EasonJim/p/7805665.html Spring Boot集成Spring Data Redis+Sp ...

随机推荐

  1. 第8周课程总结&实验报告6

    实验六 Java异常 实验目的 理解异常的基本概念: 掌握异常处理方法及熟悉常见异常的捕获方法. 实验要求 练习捕获异常.声明异常.抛出异常的方法.熟悉try和catch子句的使用. 掌握自定义异常类 ...

  2. 搜索专题: HDU1027Ignatius and the Princess II

    Ignatius and the Princess II Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K ( ...

  3. N皇后问题(递归)

    //八皇后递归解法 //#include<iostream> //using namespace std; #include<stdio.h> ] = {-,-,-,-,-,- ...

  4. 剑指offer 删除链表的节点

    给定单向链表的头指针和一个节点指针,定义一个函数在O(1)时间内删除该节点. struct ListNode { int val; ListNode *next; }; void DeleteNode ...

  5. python学习笔记(5)

    第七章   模式匹配和正则表达式 1.不用正则表达式来查找文本模式 #对于这样的一个文本查找:3个数字,一个短横线,3个数字,4个端横线,然后再是4个数字,如:415-555-4242def isPh ...

  6. java中使用SimpleDateFormat实现字符串和日期的相互转换

    java中使用SimpleDateFormat实现字符串和日期的相互转换 import java.text.ParseException; import java.text.SimpleDateFor ...

  7. thinkphp5 select对象怎么转数组?

    DB操作返回是数组.模型直接操作返回是对象 对象类型转换数组打开 database.php 增加或修改参数'resultset_type' => '\think\Collection',即可连贯 ...

  8. 博弈论(Game Theory)相关Paper阅读

    这些论文是我在研究区块链共识算法的时候搜到的,当然大多数跟区块链没什么关系,不过有些论文真的写的好,作者中不乏有诺奖得主,有些论文的结果是有违常的(比如拍卖中的价高者得),这也是这些Paper的一部分 ...

  9. linux添加头文件路径

    gcc demo.c -o demo  -I/tools/libevent/include -L/tools/libevent/lib -levent -I:头文件目录 -L:静态库目录 -l:静态库 ...

  10. GUI学习之二十六——QColorDialog学习总结

    今天要讲的是QColorDialog对话框. 一.描述 QColorDialog对话框是用来为用户提供颜色选择的对话框控件,和上一章的QFontDialog控件一样,是继承自QDialog这个基类.其 ...