springboot mysql jpa怎么jpa 定义mysql的datasource java配置

Spring Boot 揭秘与实战(二) 数据存储篇 - JPA_ IT技术精华
聚合国内IT技术精华文章,分享IT技术精华,帮助IT从业人士成长
>> 技术文章 >> 正文
Spring Boot 揭秘与实战(二) 数据存储篇 - JPA
浏览: 712 次
本文讲解 Spring Boot 基础下,如何整合 JPA 框架,编写数据访问。 环境依赖
修改 POM 文件,添加 spring-boot-starter-data-jpa 依赖。 &dependency&
&groupId&org.springframework.boot&/groupId&
&artifactId&spring-boot-starter-data-jpa&/artifactId&&/dependency& 添加 mysql 依赖。 &dependency&
&groupId&mysql&/groupId&
&artifactId&mysql-connector-java&/artifactId&
&version&5.1.35&/version&&/dependency&&dependency&
&groupId&com.alibaba&/groupId&
&artifactId&druid&/artifactId&
&version&1.0.14&/version&&/dependency& 数据源
使用 Spring Boot 默认配置, 在 src/main/resources/application.properties 中配置数据源信息。 spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/springboot_dbspring.datasource.username=rootspring.datasource.password=root 通过 Java Config 方式配置。 @Configuration@EnableJpaRepositories(&com.lianggzone.springboot.action.data.jpa&)@EntityScan(&com.lianggzone.springboot.action.data.jpa.entity&)
public class JPAConfig {} 脚本初始化
先初始化需要用到的SQL脚本。 CREATE DATABASE /*!32312 IF NOT EXISTS*/`springboot_db` /*!40100 DEFAULT CHARACTER SET utf8 */;USE `springboot_db`;DROP TABLE IF EXISTS `t_author`;CREATE TABLE `t_author` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户ID',
`real_name` varchar(32) NOT NULL COMMENT '用户名称',
`nick_name` varchar(32) NOT NULL COMMENT '用户匿名',
PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; JPA 整合方案一 通过继承 JpaRepository 接口
创建一个 Author 实体,真实的表名是 t_author,包含 id(自增主键)、 realName、 nickname 字段。 @Entity@Table(name = &t_author&)public class Author{
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name=&real_name&)
private String realN
@Column(name=&nick_name&)
private String nickN
// SET和GET方法} DAO相关
数据访问层,通过编写一个继承自 JpaRepository 的接口就能完成数据访问。值得注意的是,这个的 from 对象名,而不是具体的表名。 public interface AuthorRepository extends JpaRepository&Author, Long& {
List&Author& findAll();
@Query(&from Author where id = :id&)
Author findAuthor(@Param(&id&) Long id);} Service相关
简单的调用 DAO 相关方法。 @Service(&jpa.authorService&)public class AuthorService {
@Autowired
private AuthorRepository authorR
public List&Author& findAll() {
return this.authorRepository.findAll();
public Author findAuthor(Long id){
return this.authorRepository.findAuthor(id);
}} Controller相关
为了展现效果,我们先定义一组简单的 RESTful API 接口进行测试。 @RestController(&jpa.authorController&)@RequestMapping(value = &/data/jpa/author&)public class AuthorController {
@Autowired
private AuthorService authorS
* 查询用户列表
@RequestMapping(method = RequestMethod.GET)
public Map&String, Object& getAuthorList(HttpServletRequest request) {
List&Author& authorList = this.authorService.findAll();
Map&String, Object& param = new HashMap&String, Object&();
param.put(&total&, authorList.size());
param.put(&rows&, authorList);
* 查询用户信息
@RequestMapping(value = &/{userId:\d+}&, method = RequestMethod.GET)
public Author getAuthor(@PathVariable Long userId, HttpServletRequest request) {
Author author = this.authorService.findAuthor(userId);
if (author == null) {
throw new RuntimeException(&查询错误&);
}} JPA 整合方案二 通过调用 EntityManager 类方法
@Entity@Table(name = &t_author&)public class Author{
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name=&real_name&)
private String realN
@Column(name=&nick_name&)
private String nickN
// SET和GET方法} DAO相关
数据访问层,通过编写一个调用EntityManager 类方法。值得注意的是,这个的 from 对象名,而不是具体的表名。 public interface AuthorDao {
List&Author& findAll();
Author findAuthor(Long id);}@Repositorypublic class AuthorDaoImpl implements AuthorDao {
@PersistenceContext
private EntityManager entityM
public List&Author& findAll() {
return this.entityManager
.createQuery(&select t from Author t&, Author.class)
.getResultList();
public Author findAuthor(Long id){
return this.entityManager
.createQuery(&select t from Author t where id = ?&, Author.class)
.setParameter(1, id)
.getSingleResult();
}} Service相关
简单的调用 DAO 相关方法。 @Service(&jpa.authorService2&)public class AuthorService2 {
@Autowired
private AuthorDao authorD
public List&Author& findAll() {
return this.authorDao.findAll();
public Author findAuthor(Long id){
return this.authorDao.findAuthor(id);
}} Controller相关
为了展现效果,我们先定义一组简单的 RESTful API 接口进行测试。 @RestController(&jpa.authorController2&)@RequestMapping(value = &/data/jpa/author2&)public class AuthorController2 {
@Autowired
private AuthorService2 authorS
* 查询用户列表
@RequestMapping(method = RequestMethod.GET)
public Map&String, Object& getAuthorList(HttpServletRequest request) {
List&Author& authorList = this.authorService.findAll();
Map&String, Object& param = new HashMap&String, Object&();
param.put(&total&, authorList.size());
param.put(&rows&, authorList);
* 查询用户信息
@RequestMapping(value = &/{userId:\d+}&, method = RequestMethod.GET)
public Author getAuthor(@PathVariable Long userId, HttpServletRequest request) {
Author author = this.authorService.findAuthor(userId);
if (author == null) {
throw new RuntimeException(&查询错误&);最近在学习Spring Boot,继续前面的学习,这一次我们加入数据库和JPA。
pom.xml文件
&!-- 添加Mysql和JPA--&
& &dependency&
& &groupId&org.springframework.boot&/groupId&
& &artifactId&spring-boot-starter-data-jpa&/artifactId&
& &/dependency&
& &dependency&
&& &groupId&mysql&/groupId&
&& &artifactId&mysql-connector-java&/artifactId&
& &/dependency&
在Application.properties(在resource文件夹下新建,进行配置)文件中添加数据进行配置:
spring.datasource.url = jdbc:mysql://localhost:3306/spring_boot
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver
# Specify the DBMS
spring.jpa.database = MYSQL
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.5Dialect
package com.seawater.
import javax.persistence.*;
import javax.validation.constraints.NotN
* Created by zhouhs on .
@Table(name = &user&)
public class User {
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
public void setId(Long id) {
& this.id =
public String getName() {
public void setName(String name) {
& this.name =
public int getAge() {
public void setAge(int age) {
& this.age =
UserController
package com.seawater.
import com.seawater.Dao.UserD
import com.seawater.bean.U
import io.swagger.annotations.A
import io.swagger.annotations.ApiImplicitP
import io.swagger.annotations.ApiImplicitP
import io.swagger.annotations.ApiO
import org.springframework.web.bind.annotation.RequestM
import org.springframework.web.bind.annotation.RequestM
import org.springframework.web.bind.annotation.RequestP
import org.springframework.web.bind.annotation.RestC
import javax.annotation.R
* Created by zhouhs on .
@RestController
@RequestMapping(value = &/user&)
@Api(description = &用户&)
public class UserController {
UserDao userDAO;
@ApiOperation(value = &添加用户&)
@ApiImplicitParams({
&& @ApiImplicitParam(name = &name& , value = &name& , paramType = &query& , required = true ),
&& @ApiImplicitParam(name = &age& , value = &age& , paramType = &query& , required = true )
@RequestMapping(value = &/addUser& , method = RequestMethod.POST)
public String addUser(@RequestParam(value = &name&) String name,@RequestParam(value = &age&) int age){
& User user = new User();
& user.setName(name);
& user.setAge(age);
& userDAO.save(user);
& return &add user success !&;
@ApiOperation(value = &查找用户&)
@ApiImplicitParam(name = &id& , value = &id& , paramType = &query& , required = true , dataType = &int&)
@RequestMapping(value = &/findById& , method = RequestMethod.POST)
public String findById(@RequestParam(value = &id&) Long id){
& User user = userDAO.findById(id);
& if(user == null){
&& return &error&;
&& return &name:& + user.getName() + & , age:& + user.getAge();
@ApiOperation(value = &查询所有用户&)
@RequestMapping(value = &/findAll& , method = RequestMethod.POST)
public Iterable findAll(){
& Iterable&User& userList = userDAO.findAll();
& return userL
@ApiOperation(value = &删除用户&)
@ApiImplicitParam(name = &id& , value = &id& , paramType = &query& , required = true , dataType = &int&)
@RequestMapping(value = &/deleteById& , method = RequestMethod.POST)
public String deleteById(@RequestParam(value = &id&) Long id){
& userDAO.delete(id);
& return &delete success !&;
数据表(id定义为Integer):
package com.seawater.D
import com.seawater.bean.U
import org.springframework.data.repository.CrudR
* Created by zhouhs on .
public interface UserDao extends CrudRepository&User, Long& {
public User findById(Long id);
然后启动项目:访问http://localhost:8081/swagger-ui.html
方法我就不一一操作了。
相关文章列表:
<a href="/html/2014/Java_.html" class="title" title="N个数选M(MN个数选M(M&=N)个数,打印出所有...JPA是sun提出的一个对象持久化规范,各JavaEE应用服务器自主选择具体实现,JPA的设计者是hibernate框架的作者,因此Hibernate作为Jboss服务器中JPA的默认实现,Oracle的Weblogic使用EclipseLink(以前叫TopLink)作为...
使用spring jpa,报no declaration can be found for element 'jpa:repositories'错误的解决方案 margin-top:20margin-bottom:20line-height:28.8letter-spacing:0.5font-size:16word-wrap:break-...
例如每篇文章都有一个User域,但是我只需要user的名称和ID就好,我使用spring data jpa,一查就是一堆数据,其中还有user的密码,这样很不好,不知道怎么解决。只有在验证用户的时候需要查询密码,其他时候均不需要...
在上篇文章&a href="/springboot//springboot%28%E4%BA%8C%29-web%E7%BB%BC%E5%90%88%E5%BC%80%E5%8F%91.html"&springboot(二):web综合开发中简单介绍了一下spring data jpa的...
项目使用的是sping集成hibernate想拦截sql...了解到hibernate有拦截器可以使用,但是看了现项目的配置,是使用了jpa,配置如下 ``` class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"& ...
项目使用的是sping集成hibernate想拦截sql...了解到hibernate有拦截器可以使用,但是看了现项目的配置,是使用了jpa,配置如下 ``` class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"& ...
在官网没看到spring-data-jpa分页使用的栗子,所有不太会用。Page&Course&findCourseSortByHot(Pageable pageable);spring-data-jpa在发出sql语句时,是根据方法名中的SortByHot呢还是根据Pageable中设置的sort,...
原生的sql,在mysql中可以`insert into table(column1,column2)values(),(),()`这样批量插入很多数据,jpa中我看好像没有可以批量插入的。请问各位有吗?看好多帖说`EntityManager.persist(),`然后多少条flush(),...
spring 3.2 spring data jpa 1.3 hibernate4 db为mysql5.5.default-storage-engine=INNODB ` 错误: ` Executing an update/nested exception is javax.persistence.TransactionRequiredException:...
在某些案例中,你可以见识到重新访问现有的、传统的框架带来的积极效果,比如说你的 JPA 的实现。本文系国内[ITOM][1]管理平台[OneAPM][2]编译呈现。多年以前,笔者在为一家世界顶级汽车公司做电子商务网站项目时,...
font-size:14px"&JPA+Mysql开发过程中存储数据,遇到中文乱码:
&/span& span style="font-family:KaiTi_GB2312;font-size:14px"&IDE:Eclipse&/span&&/p& span style="font-family:KaiTi_GB2312;font-...
手中处理一个项目,持久层采用hibernate+jpa。实体类通过注解来绑定到table。我想用一个实体基类来管理常用的字段,比如createBy、createTime等, 然后用泛型的dao来保存这些常用字段,应该如何处理?特别说明的是,...
使用jpa的仓库接口来查询数据,本意是根据条件来查询一个实体的指定属性字段,但是现在却把这个实体的所有属性都查出来了。问问大神们怎么解决。采用的是实现JpaSpecificationExecutor接口:代码如下: 1 2 3 4 5 6 ...
绍在一起使用 jpa,hibernate 和 spring 时配置 ehcache 二级缓存的步骤。
在一个JPA Entity中定义了java.util.Date类型的LastUpdateTime 和 CreateTime 两个字段实例。现在想要的需求是在执行 EntityManager 的 persist 方法(即执行SQL 的Insert)时 会自动给 CreateTime和 LastUpdateTime...
hibernate-jpa2.0+spring3.2.3+tomcat7,本来好好的,忽然有一天出现这个问题,persistence.xml文件和applicationContext.xml文件未做过改动,jar包也没动过,到底是什么原因啊~ 以下是错误列表,部分省略… 严重:`...
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:273) at com.sun.proxy.$Proxy21.persist(Unknown Source) at ...
原生的sql,在mysql中可以insert into table(column1,column2)values(),(),()这样批量插入很多数据,jpa中我看好像没有可以批量插入的。请问各位有吗?看好多帖说EntityManager.persist(),然后多少条flush(),clear...
由于各种orm框架层出不穷,为了统一大家,就出现了jpa这一层接口规范,不同的orm框架都去实现这一规范,然后我们就只关心使用jpa的编程接口来进行编程,不用再关系底层到底使用的是那种orm框架,同时也很容易切换...
未解决问题?到论坛提问试试吧!
你可能感兴趣}

我要回帖

更多关于 spring boot jpa配置 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信