一、环境
1、hibernate 5.3.1.Final
Maven POM格式
<!-- hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.3.1.Final</version> </dependency>
2、IDE IntelliJ IDEA 2020
版本很关键,不写版本号发技术文章就是耍流氓
二、新增、修改、删除和执行SQL语句
2.1 User实体类,使用注解就可以了不用创建表对应的*.hbm.xml文件了。减少维护和出错率。使用
Lombok减少代码量,Lombok的POM格式
<!-- lombok from repository 简化实体类代码--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency>
package com.yadinghao.entity.po; import lombok.Data; import javax.persistence.Entity; import javax.persistence.Id; @Data @Entity(name = "user") public class User { public String age; @Id public String name; }
2.2 实际代码
package com.yadinghao.demo; import com.yadinghao.entity.po.User; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.query.NativeQuery; import org.hibernate.query.Query; import org.hibernate.service.ServiceRegistry; import javax.jws.soap.SOAPBinding; import java.sql.SQLException; import java.util.List; public class hibernatedemo { //POJO 创建数据库表 public static void main(String[] args) { Configuration config = new Configuration(); //config.configure("hibernate.cfg.xml"); // 创建工厂 ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build(); SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); // creating session object Session session = sessionFactory.openSession(); User user= new User(); user.setAge("41"); user.setName("张渔歌"); session.beginTransaction(); session.save(user); //新增 session.update(user);//修改 session.delete(user);//删除 session.getTransaction().commit(); String sql = "select name,age from user"; Query<User> query = session.createNativeQuery(sql,User.class); //session.get("name"); // 3)获得结果 List<User> list = query.list(); System.out.println(list.size()); for(User u : list){ System.out.println(u.getName()+":"+u.getAge()); } } }
session.save(user); //新增
session.update(user);//修改
session.delete(user);//删除
这组方法应该通
执行SQL语句就不通用了。之前的SQLQuery、addEntity都废弃了。
好了就写到这吧