今天配置了一下springboot 的jpa零xml配置,最终配置好了,也作为springboot和jpa的学习配置分享一下,能搜到的配置大部分都是基于xml的配置。
jpa的配置参考慕课网,主要是xml配置
springboot的学习参考
application.yml
db:
driver: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/springbootdb
username: root
password: 密码
hibernate:
show_sql: true
format_sql: true
ejb.naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy
dialect: org.hibernate.dialect.MySQL5InnoDBDialect
hbm2ddl.auto: update
packages.to.scan: com.gwc
jpa的配置主要包括以下三个地方
- 配置数据源dataSource
- 配置EntityManagerFactory
- 事务管理器配置
具体配置如下(关键位置已经有了注释)
package com.gwc.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.hibernate5.HibernateExceptionTranslator;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.Properties;
/**
* jpa的配置类,包括数据源,事务管理等
* Created by gwcheng on 2017/4/21.
*/
// 标明该类使用Spring基于Java的配置
@Configuration
// 读取配置文件的,通过Environment读取
@PropertySource("classpath:application.yml")
// scan the package of the annotated configuration class for Spring Data repositories
@EnableJpaRepositories(basePackages = "com.gwc.dao")
// Enables Spring's annotation-driven transaction management
@EnableTransactionManagement
public class JpaConfig {
@Autowired
private Environment env;
/**
* 1.配置数据源
*
* @return DataSource
*/
@Bean
public DataSource dataSource() {
DruidDataSource source = new DruidDataSource();
source.setDriverClassName(env.getRequiredProperty("db.driver"));
source.setUrl(env.getRequiredProperty("db.url"));
source.setUsername(env.getRequiredProperty("db.username"));
source.setPassword(env.getRequiredProperty("db.password"));
return source;
}
/**
* 2.配置EntityManagerFactory
*
* @return
*/
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
// 配置数据源
factory.setDataSource(dataSource());
// VendorAdapter
factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
// entity包扫描路径
factory.setPackagesToScan(env.getRequiredProperty("packages.to.scan"));
// jpa属性
factory.setJpaProperties(hibernateProperties());
factory.afterPropertiesSet();
return factory;
}
/**
* 3.事务管理器配置
*
* @return
*/
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager manager = new JpaTransactionManager();
manager.setEntityManagerFactory(entityManagerFactory().getObject());
return manager;
}
/**
* 把HibernateExceptions转换成DataAccessExceptions
*/
@Bean
public HibernateExceptionTranslator hibernateExceptionTranslator() {
return new HibernateExceptionTranslator();
}
/**
* hibernate配置
* @return
*/
private Properties hibernateProperties() {
Properties properties = new Properties();
// 显示sql语句
properties.put("hibernate.show_sql", env.getRequiredProperty("hibernate.show_sql"));
// 格式化sql语句
properties.put("hibernate.format_sql", env.getRequiredProperty("hibernate.format_sql"));
// 方言
properties.put("hibernate.dialect", env.getRequiredProperty("hibernate.dialect"));
// 自动生成表
properties.put("hibernate.hbm2ddl.auto", env.getRequiredProperty("hibernate.hbm2ddl.auto"));
// 名字策略
properties.put("hibernate.ejb.naming_strategy", env.getRequiredProperty("hibernate.ejb.naming_strategy"));
return properties;
}
}
开发自己的dao继承JpaRepository
package com.gwc.dao;
import com.gwc.entity.SysMenu;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* Created by gwcheng on 2017/4/21.
*/
public interface SysMenuRepository extends JpaRepository<SysMenu,Long> {
}
SysMenu是系统菜单类
package com.gwc.entity;
import com.gwc.enums.MenuType;
import javax.persistence.*;
import java.util.Date;
/**
* 系统菜单
* Created by gwcheng on 2017/4/21.
*/
@Entity
public class SysMenu {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
/*主键*/
private Long id;
/*
名称
*/
@Column(length = 20)
private String name;
/*
父id
*/
private Long parentId;
/*
顺序
*/
@Column(name = "orders")
private Integer order;
/*
类型,module(模块),page(页面)
*/
@Column(length = 6)
private String type;
/*
链接(type为page时有url)
*/
@Column(length = 32)
private String url;
/*
图标(type为module是会有图标)
*/
@Column(length = 32)
private String icon;
/*
创建时间
*/
private Date createTime;
/*
修改时间
*/
private Date updateTime;
// ... 省去getter setter方法和toString方法
}
测试用例如下
package com.gwc;
import com.gwc.config.MainApplication;
import com.gwc.dao.SysMenuRepository;
import com.gwc.entity.SysMenu;
import com.gwc.enums.MenuType;
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.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Date;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MainApplication.class)
public class SysMenuRepositoryTests {
@Autowired
SysMenuRepository sysMenuRepository;
@Test
public void testPageAndSort() {
Sort.Order order = new Sort.Order(Sort.Direction.DESC,"order");
Sort sort = new Sort(order);
Pageable pageable = new PageRequest(0,2,sort);
Page<SysMenu> page = sysMenuRepository.findAll(pageable);
for(SysMenu sysMenu:page.getContent()){
System.out.println(sysMenu);
}
}
@Test
public void testSort(){
Sort sort = new Sort(Sort.Direction.DESC, "order");
List<SysMenu> sysMenuList = sysMenuRepository.findAll(sort);
for(SysMenu sysMenu : sysMenuList) {
System.out.println("排序字段:"+sysMenu.getOrder());
}
}
@Test
public void testSave(){
SysMenu sysMenu = new SysMenu();
sysMenuRepository.save(sysMenu);
}
@Test
public void testFindAll(){
List<SysMenu> sysMenuList = sysMenuRepository.findAll();
for(SysMenu sysMenu:sysMenuList){
System.out.println(sysMenu);
}
}
@Test
public void testDelete(){
sysMenuRepository.delete(1L);
}
@Test
public void testFindOne(){
SysMenu sysMenu = sysMenuRepository.findOne(1L);
System.out.println(sysMenu);
}
}
参考文献
Spring Boot学习笔记-自定义配置
Spring Boot学习笔记-开发第一个应用程序
轻松愉快之玩转SpringData