Springboot Jpa save 操作无效
1.先贴上一份 jpa基本配置
@SpringBootApplication
@EnableTransactionManagement
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication .class, args);
}
}
@Configuration
public class JpaConfig{
@Autowired
private DynamicDataSource dynamicDataSource;
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.xxx.xxx.entity");
factory.setJpaProperties(hibernateProperties());
factory.setDataSource(dynamicDataSource);
return factory;
}
@Bean("tx")//注意这个bean 事务管理器的名字是 tx ,后面方法用的时候记得加上这个名字
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory);
return txManager;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
// 显示sql语句
properties.put("hibernate.show_sql", true);
// 格式化sql语句
properties.put("hibernate.format_sql", true);
// 方言
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
// 自动生成表
properties.put("hibernate.hbm2ddl.auto", "update");
//设置事务提交模式
// properties.put("hibernate.connection.autocommit",false);
// properties.put("org.hibernate.flushMode", "COMMIT");
// properties.put("hibernate.enable_lazy_load_no_trans",true);
return properties;
}
}
2.service调用
@Transactional(value = "tx") //代表引用上面配置的事务管理器
public SysPrivilege createPrivilegeIfNotFound(String name) {
SysPrivilege privilege = privilegeRepository.findPrivilegeByName(name);
if (privilege == null) {
privilege = new SysPrivilege();
privilege.setName(name);
privilege = privilegeRepository.save(privilege);
}
return privilege;
}
最后结果:insert 语句打印出来了
Hibernate:
insert
into
sys_privilege
(name)
values
(?)
Hibernate:
select
sysprivile0_.id as id1_0_,
sysprivile0_.icon as icon2_0_,
sysprivile0_.name as name3_0_,
sysprivile0_.`
order` as order4_0_,
sysprivile0_.parentId as parentId5_0_,
sysprivile0_.parentName as parentNa6_0_,
sysprivile0_.perms as perms7_0_,
sysprivile0_.type as type8_0_,
sysprivile0_.url as url9_0_ from
sys_privilege sysprivile0_
where
sysprivile0_.name=?
3,如果想使用默认的事务管理器,也可以写一个类,类加上@Component
实现TransactionManagementConfigurer接口,该接口只有一个方法返回PlatformTransactionManager。其中返回的PlatformTransactionManager就表示这是默认的事务处理器,这样在Transactional注解上就不需要声明是使用哪个事务管理器了。
参考链接:http://www.importnew.com/24138.html