solon 的hibernate 5.6.x
适配插件,并对部分接口进行封装方便进行CURD。如果您常用hibernate,即能快速上手。
hibernate 6、jdk11/17+ 请使用2.x版本:
https://gitee.com/lingkang_top/hibernate-solon-plugin/tree/dev2.x/
<dependency>
<groupId>top.lingkang</groupId>
<artifactId>hibernate-solon-plugin</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>4.0.3</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.1.0</version>
</dependency>
尝新使用快照版?看这里:
SNAPSHOT - 快照版本
app.yml
配置
db1:
jdbcUrl: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&autoReconnect=true&rewriteBatchedStatements=true
driverClassName: com.mysql.cj.jdbc.Driver
username: root
password: 123456
minIdle: 1
maxPoolSize: 10
MyConfig.java
配置数据库
@Configuration
public class MyConfig {
@Bean
public DataSource db1(@Inject("${db1}") HikariDataSource ds) {
ds.setPoolName("db1");
ds.setMaximumPoolSize(10);
return ds;
}
@Bean
public SessionFactory sessionFactory(@Inject DataSource dataSource) {
Properties properties = new Properties();
// 设置数据源
properties.put(AvailableSettings.DATASOURCE, dataSource);
/**
* create:表示启动的时候先drop,再create
* create-drop: 也表示创建,只不过再系统关闭前执行一下drop
* update: 这个操作启动的时候会去检查schema是否一致,如果不一致会做scheme更新
* validate: 启动时验证现有schema与你配置的hibernate是否一致,如果不一致就抛出异常,并不做更新
*/
properties.put(AvailableSettings.HBM2DDL_AUTO, "validate");
// 打印SQL
// properties.put(AvailableSettings.SHOW_SQL, "true");
HibernateConfiguration configuration = new HibernateConfiguration();
// 扫描实体类所在的包
configuration.addScanPackage("top.lingkang.h5.test.entity");
// 或者一个个加
// configuration.addAnnotatedClass(UserEntity.class);
configuration.setProperties(properties);
return configuration.buildSessionFactory();
}
}
top.lingkang.h5.test.entity.UserEntity
/**
* @author lingkang
* created by 2023/9/27
* mysql:
*
* <pre>
* CREATE TABLE `n_user` (
* `id` varchar(50) NOT NULL,
* `username` varchar(50) DEFAULT NULL,
* `password` varchar(64) DEFAULT NULL,
* `nickname` varchar(50) DEFAULT NULL,
* `sex` varchar(2) DEFAULT NULL,
* `create_time` datetime DEFAULT NULL,
* `update_time` datetime DEFAULT NULL,
* PRIMARY KEY (`id`)
* ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
* </pre>
*/
@Data
@Entity
@Table(name = "n_user")
public class UserEntity {
@Id
private String id;
@Column
private String username;
@Column
private String password;
@Column
private String nickname;
@Column
private String sex;
@Column(name = "create_time")
private Date createTime;
@Column(name = "update_time")
private Date updateTime;
@PrePersist
public void prePersist() {
if (createTime == null)
createTime = new Date();
if (updateTime == null)
updateTime = createTime;
else
updateTime = new Date();
}
@PreUpdate
public void preUpdate() {
updateTime = new Date();
}
}
使用
// 注入 controller、service、component等
@Inject
private SessionFactory sessionFactory;
// 代码调用
@Test
public void sessionTest(){
List list = sessionFactory.openSession().createQuery(
"select e from UserEntity e"
).list();
System.out.println(list);
}
@Transaction// 更新/删除操作必须使用事务,遵循hibernate
public void updateTime(){
// 使用 getCurrentSession 时也需要开启事务
sessionFactory.getCurrentSession().createQuery("update UserEntity set updateTime=?1")
.setParameter(1,new Date()).executeUpdate();
}
Dao
基于上面配置,定义UserDao
接口,必须继承HibernateDao
, 同时添加@Dao
注解,用于扫描
@Dao // 必须添加这个,当前版本solon(2.5.10)不支持包扫描环绕代理接口
public interface UserDao extends HibernateDao<UserEntity> {
@Query("select count(e.id)>0 from UserEntity e")
boolean exists();
// 只查询部分字段 / 类型转化 UserEntity → UserVO ,字段必须带上 as 别名
@Query("select e.id as id,e.username from UserEntity e")
List<UserVO> getAllVo();
@Modifying// 涉及更新操作
@Query("update UserEntity set password=?1")
int updatePasswordInt(String password);
@Modifying
@Query("delete from UserEntity where id=?1")
int delete1(String id);
}
PS:只查询部分字段到bean、map,必须在Dao中执行,而且每个字段必须带上 as 别名映射
调用
@Inject
private UserDao userDao;
public void getAll() {
System.out.println(userDao.findAll());
}
@Transaction // 涉及更新操作需要事务
public void updateTest(){
userDao.updatePassword(UUID.randomUUID().toString());
}
https://gitee.com/lingkang_top/hibernate-solon-plugin/tree/master/src/test
https://gitee.com/lingkang_top/hibernate-solon-plugin/blob/master/doc/example.md
hibernate
在每次执行完update
/delete
之后,会把数据先存放在缓存中,不会立即更新到数据库,可以调用session.flush()
手动把更新的数据刷新到数据库中,然后再执行查操作即可。
不能使用组合主键。hibernate-solon-plugin
底层没有对组合主键进行适配。
已经禁用多数据源,不支持多数据源!
EntityManager
EntityManager
可以通过 sessionFactory.createEntityManager()
获取,使用entityManager
操作的数存在于缓存中,非通过entityManager
修改了数据,查询到的仍是原数据。可以使用entityManager.clear()
进行清理缓存,获取最新数据。
事务默认只实现了下面的传播机制,没有的就是不支持。
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。