springboot-jpa获取session
springboot获取hibernate的session进行更精细的SQL操作,默认的jpa并不能满足一些复杂需求(可能是我把需求设计复杂了)
通过查看JpaRepository
的底层实现,发现是通过EntityManager
进行数据库会话操作,因此进一步获取它管理的会话。
@Autowired
private UserDao userDao;
@Autowired
private EntityManager entityManager;
@Transactional// 涉及更新删除,需要开启事务
@Override
public void run(ApplicationArguments args) throws Exception {
// 获取会话,,,使用 unwrap 返回 EntityManager 的底层实现
Session session = entityManager.unwrap(Session.class);
User byUsername = userDao.findByUsername("123");
if (byUsername == null) {
User user = new User();
user.setUsername("123");
user.setPassword("123");
user.setNickname("管理员");
session.save(user);
// springboot 2.3.12 使用的是 hibernate 5.4.x
List username = session.createQuery("from User u where username=:username")
.setParameter("username", "123").list();
System.out.println(username);
Role role = new Role();
role.setName("admin");
session.save(role);
UserToRole userToRole = new UserToRole();
userToRole.setUser(user);
userToRole.setRole(role);
session.save(userToRole);
Authority authority = new Authority();
authority.setUrl("/**");
session.save(authority);
Menu menu = new Menu();
menu.setUrl("/index");
menu.setSeq(0);
menu.setTitle("主页");
session.save(menu);
session.save(new RoleToAuthority(role, authority));
session.save(new RoleToMenu(role, menu));
}
// 此处要注意 使用User的细节
List username = session.createQuery("from User u where username=:username")
.setParameter("username", "123").list();
System.out.println(username);
}
我们注意到上面使用User的细节,不是使用表名ad_user
,而是直接使用实体User,
@Entity
@Table(name = "ad_user") // import javax.persistence.Table
@org.hibernate.annotations.Table(appliesTo = "ad_user", comment = "用户表")
@Data
public class User
// 对应 User
List username = session.createQuery("from User u where username=:username")
.setParameter("username", "123").list();
@Entity(name = "ad_user")
//@Table(name = "ad_user") // import javax.persistence.Table
@org.hibernate.annotations.Table(appliesTo = "ad_user", comment = "用户表")
@Data
public class User
// 对应 ad_user
List username = session.createQuery("from ad_user u where username=:username")
.setParameter("username", "123").list();
建议使用第一种!