首先使用Maven工程和junit完成hibernate对数据库的简单操作,完成之后在使用SpringBoot集成Jap完成hibernate对数据库的操作。本文仅供新手学习查看,具体线上使用需要对代码继续进行相关优化。
1、先创建一个Maven工程,导入相关依赖。
(资料图片仅供参考)
org.projectlombok lombok 1.18.16 mysql mysql-connector-java 8.0.26 junit junit 4.11 test org.hibernate hibernate-core 5.6.14.Final
2、在resources目录下创建hibernate.cfg.xml
com.mysql.cj.jdbc.Driver jdbc:mysql://localhost:3306/user-mode root 1234qwer org.hibernate.dialect.MySQLDialect true true
3、创建一个实体类
@Datapublic class User {private Long id; private String name; private String password; private String account; private String email;private String secondName;}
4、在resources目录下创建一个mapper目录,在mapper目录下面创建User实体类的映射文件User.hbm.xml
配置完上述配置之后,接下来我们就可以使用junit进行测试了,先在test目录下面创建一个测试类UserTest。
5、使用junit添加一个User用户
@org.junit.Test public void TestSave(){ //读取 hibernate.cfg.xml配置文件, 创建会话工厂 SessionFactory Configuration configuration = new Configuration().configure(); SessionFactory sessionFactory = configuration.buildSessionFactory(); // 获取 Session 对象 Session openSession = sessionFactory.openSession(); //开启事务 openSession.beginTransaction(); User user = new User(); user.setAccount("hibernateTest01"); user.setName("hibernateTest01"); user.setPassword("ASWDEWSA"); user.setEmail("hibernate02@hbm.com"); user.setSecondName("hibernateTest01"); openSession.save(user); //提交事务 openSession.getTransaction().commit(); }
执行之后,控制台没有报红,说明添加成功了。可以给上述代码做下优化,帮助我们更方便的完成其他操作。
private Session openSession; @Before public void before(){ //读取 hibernate.cfg.xml配置文件, 创建会话工厂 SessionFactory Configuration configuration = new Configuration().configure(); SessionFactory sessionFactory = configuration.buildSessionFactory(); // 获取 Session 对象 openSession = sessionFactory.openSession(); } @org.junit.Test public void TestSave(){// //读取 hibernate.cfg.xml配置文件, 创建会话工厂 SessionFactory // Configuration configuration = new Configuration().configure(); // SessionFactory sessionFactory = configuration.buildSessionFactory();// // 获取 Session 对象 // Session openSession = sessionFactory.openSession(); //开启事务 openSession.beginTransaction(); User user = new User(); user.setAccount("hibernateTest01"); user.setName("hibernateTest01"); user.setPassword("ASWDEWSA"); user.setEmail("hibernate02@hbm.com"); user.setSecondName("hibernateTest01"); openSession.save(user); //提交事务 openSession.getTransaction().commit(); }
@After public void after(){ if (openSession != null){ openSession.close(); }}
实现更新、删除、查询,查询有许多种方法,后面可以进行深入学习。
@org.junit.Test public void testUpdate(){ //开启事务 openSession.beginTransaction(); User user = new User(); user.setId(8L); user.setAccount("hibernateTest03"); user.setName("hibernateTest03"); user.setPassword("ASWDEWSAW"); user.setEmail("hibernate03@hbm.com"); user.setSecondName("hibernateTest03"); openSession.update(user); //提交事务 openSession.getTransaction().commit(); } @org.junit.Test public void testDelete(){ //开启事务 openSession.beginTransaction(); User user = new User(); user.setId(8L); openSession.delete(user); //提交事务 openSession.getTransaction().commit(); } @org.junit.Test public void testFind(){ User user = new User(); user.setId(8L); //已过时 Criteria criteria = openSession.createCriteria(User.class); List list = criteria.list(); for (Object o : list) { System.out.println(o); } List fromUser = openSession.createQuery("from User").list(); fromUser.forEach(System.out::println); }
到这里通过maven简单的使用hibernate的操作就完成了,后面我们使用SpringBoot集成Jpa。
6、首先调整我们的maven项目,添加springboot相关依赖以及jpa依赖。
org.springframework.boot spring-boot-starter-parent 2.2.11.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-test test org.springframework.boot spring-boot-starter-data-jpa com.alibaba druid 1.2.16
7、创建Springboot启动类
/** * @date: 2023-05-11 13:29 */@SpringBootApplicationpublic class HibernApplication { public static void main(String[] args) { SpringApplication.run(HibernApplication.class,args); }}
8、在resources目录下创建yml文件
server: port: 8800spring: application: name: hibernate profiles: active: prod
spring: jpa: properties: hibernate: dialect: org.hibernate.dialect.MySQLDialect new_generator_mappings: false format_sql: true #show_sql: true database: mysql show-sql: true #当数据库表没有该属性字段,会根据实体类相关字段自动创建一个字段,如secondName在数据库创建的为second_name hibernate: ddl-auto: update datasource: driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource url: jdbc:mysql://localhost:3306/user-mode?serverTimezone=Asia/Shanghai username: root password: 1234qwer
9、调整之前创建的实体类
@Data@Entity@Table(name = "tb_user")public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id",nullable = false) private Long id; private String name; private String password; private String account; private String email; @Column(name = "second_name",nullable = false) private String secondName;}
10、创建一个dao层接口继承jpa接口
public interface UserMapper extends JpaRepository{ }
后面就跟正常调用方法一样,通过注入UserMapp接口,进行调用。
@Servicepublic class UserServiceImpl implements IUserService { @Autowired private UserMapper userMapper; @Override public ListfindAll() { List userIterable = userMapper.findAll(); return userIterable; } @Override public User save() { User user = new User(); user.setAccount("hibernateJPa03"); user.setName("hibernateJPa03"); user.setPassword("ASWDEWSAW"); user.setEmail("hibernateJPa03@hbm.com"); user.setSecondName("hibernateJPa03"); User save = userMapper.save(user); return save; } @Override public User update() { User user = new User(); user.setId(5L); user.setAccount("hibernateJPa03"); user.setName("hibernateJPa03"); user.setPassword("ASWDEWSAW"); user.setEmail("hibernateJPa03@hbm.com"); user.setSecondName("hibernateJPa03"); User save = userMapper.save(user); return save; } @Override public User delete() { User user = new User(); user.setId(10L); userMapper.delete(user); return null; } @Override public User userById() { // Iterable allById = userMapper.findAllById(Arrays.asList(1L)); Optional userOptional = userMapper.findById(4L); if (!userOptional.isPresent()){ return null; } User user = userOptional.get(); return user; }}
创建controller类编写一个接口进行测试。
@RestController@RequestMapping("/admin/user")public class UserController { @Autowired private IUserService userService; @GetMapping public String crudUser(){ ListuserList = userService.findAll(); userList.forEach(System.out::println); User user = userService.userById(); System.out.println(user); return "操作执行成功!!!"; }}
调用接口执行过后,查看控制台输出。
数据查询成功。至此springboot集成JPA就完成了。里面有很多方法,时间充足可以试试不同的方法。
Copyright @ 2015-2022 IT研究网版权所有 关于我们 备案号: 沪ICP备2022005074号-4 联系邮箱:58 55 97 3@qq.com