简介
Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全自动的orm框架,hibernate可以自动生成SQL语句,自动执行,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。Hibernate可以应用在任何使用JDBC的场合,既可以在Java的客户端程序使用,也可以在Servlet/JSP的Web应用中使用,最具革命意义的是,Hibernate可以在应用EJB的JaveEE架构中取代CMP,完成数据持久化的重任
搭建Hibernate框架
1.创建一个maven项目
创建与数据库相对应的实体类user:
package com.hxc.one.entity; import java.io.Serializable; import java.sql.Date; import java.sql.Timestamp; public class User implements Serializable{ public User() { super(); // TODO Auto-generated constructor stub } public User(String userName, String userPwd, String realName, String sex, Date birthday, Timestamp createDatetime, String remark) { super(); this.userName = userName; this.userPwd = userPwd; this.realName = realName; this.sex = sex; this.birthday = birthday; this.createDatetime = createDatetime; this.remark = remark; } private Integer id; private String userName; private String userPwd; private String realName; private String sex; private Date birthday; private Timestamp createDatetime; private String remark; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPwd() { return userPwd; } public void setUserPwd(String userPwd) { this.userPwd = userPwd; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public Timestamp getCreateDatetime() { return createDatetime; } public void setCreateDatetime(Timestamp createDatetime) { this.createDatetime = createDatetime; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } @Override public String toString() { return "User [id=" + id + ", userName=" + userName + ", userPwd=" + userPwd + ", realName=" + realName + ", sex=" + sex + ", birthday=" + birthday + ", createDatetime=" + createDatetime + ", remark=" + remark + "]"; } }
在实体类的同包路径下,创建与实体类对应的配置文件user.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <!-- class标签中: name:实体类的全路径 table:实体类对应数据库中的表 id 标签: name:实体类中的属性(映射的是表的主键) type:属性类对应的类型 co'lumn:属性对应的表中的哪一个列段 property: name;实体类中的属性(映射的是表的非主键) type:属性对应的类型 column:属性对应的表中的哪一个列段 1.建模hibernate.cfg.xml 对象,从中拿到了com/hxc/one/entity/user.hbm.xml 2.建模了user.hbm.xml 拿到了com.hxc.one.entity.User和t_hibernate_user 3.User user=Class.forName("com.hxc.one.entity.User").newInstance(); Field userNameField = user.getClass("userName"); Field userPwdField = user.getClass("userPwd"); select user_name,user_pwd,real_name , ... from t_hibernate_user User [id=7, userName=吃吃吃, userPwd=mima, realName=null, sex=null, birthday=null, createDatetime=2018-10-17 15:01:55.0, remark=null] User [id=9, userName=吃吃吃22, userPwd=mima, realName=null, sex=null, birthday=null, createDatetime=2018-10-17 15:08:45.0, remark=null] userNameField.set(user,吃吃吃) userPwdField.set(user,mima) ... 最后user中的所有属性值都有了 4.循环上一步操作,最终所有user实例都放入了list集合中就是List list --> <class name="com.hxc.one.entity.User" table="t_hibernate_user"> <id name="id" type="java.lang.Integer" column="id"> <generator class="increment" /> </id> <property name="userName" type="java.lang.String" column="user_name"> </property> <property name="userPwd" type="java.lang.String" column="user_pwd"> </property> <property name="realName" type="java.lang.String" column="real_name"> </property> <property name="sex" type="java.lang.String" column="sex"> </property> <property name="birthday" type="java.sql.Date" column="birthday"> </property> <property insert="false" update="false" name="createDatetime" type="java.sql.Timestamp" column="create_datetime"> </property> <property name="remark" type="java.lang.String" column="remark"> </property> </class> </hibernate-mapping>
在Java Resources —>src/main/resources目录下创建hibernate.cfg.xml文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 1. 数据库相关 --> <property name="connection.username">root</property> <property name="connection.password">123</property> <property name="connection.url">jdbc:mysql://localhost:3306/mytable?useUnicode=true&characterEncoding=UTF-8 </property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 配置本地事务(No CurrentSessionContext configured!) --> <property name="hibernate.current_session_context_class">thread</property> <!-- 2. 调试相关 --> <property name="show_sql">true</property> <property name="format_sql">true</property> <!-- 3. 添加实体映射文件 --> <mapping resource="com/hxc/one/entity/user.hbm.xml" /> </session-factory> </hibernate-configuration>
hibernate的查询案例
package com.hxc.one.test; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; /** * hibernate 中查询案例 * * @author 旧城 * */ public class QueryDemo { public static void main(String[] args) { // 对hibernate.cfg.xml进行建模拿到sessionfactory工厂 Configuration configuration = new Configuration().configure("/hibernate.cfg.xml"); SessionFactory sessionFactory = configuration.buildSessionFactory(); // 通过工厂获取到session会话(操作数据库的) Session session = sessionFactory.openSession(); // 直接操作数据库 List list = session.createQuery("from User").list(); for (Object object : list) { System.out.println(object); } // 关闭资源 session.close(); } }
效果如下:
hibernate中增加案例
package com.hxc.one.test; import java.sql.Timestamp; import java.sql.Date; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import com.hxc.one.entity.User; /** * hibernate中增加案例 * @author 旧城 * */ public class AddDemo { public static void main(String[] args) { // 对hibernate.cfg.xml进行建模拿到sessionfactory工厂 Configuration configuration = new Configuration().configure("/hibernate.cfg.xml"); SessionFactory sessionFactory = configuration.buildSessionFactory(); // 通过工厂获取到session会话(操作数据库的) Session session = sessionFactory.openSession(); //获取事务对象 Transaction transaction=session.beginTransaction(); // 直接操作数据库 session.save(new User("小李飞刀", "123456", "小李飞刀", "男", new Date(System.currentTimeMillis()),new Timestamp(System.currentTimeMillis()), "天下第一")); //显示数据 List list = session.createQuery("from User").list(); for (Object object : list) { System.out.println(object); } //提交事务 transaction.commit(); // 关闭资源 session.close(); } }
效果如下:
hibernate的修改案例
package com.hxc.one.entity; import java.sql.Date; import java.sql.Timestamp; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class EditDemo { /** * hibernate中修改案例 * * @author 旧城 * */ public static void main(String[] args) { // 对hibernate.cfg.xml进行建模拿到sessionfactory工厂 Configuration configuration = new Configuration().configure("/hibernate.cfg.xml"); SessionFactory sessionFactory = configuration.buildSessionFactory(); // 通过工厂获取到session会话(操作数据库的) Session session = sessionFactory.openSession(); // 获取事务对象 Transaction transaction = session.beginTransaction(); // 直接操作数据库 User user= session.get(User.class, 15); System.out.println(user); user.setRealName("小李飞刀3"); //显示数据 List list = session.createQuery("from User").list(); for (Object object : list) { System.out.println(object); } // 提交事务 transaction.commit(); // 关闭资源 session.close(); } }
效果如下:
hibernate的删除案例
package com.hxc.one.entity; import java.sql.Date; import java.sql.Timestamp; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; /** * @author 旧城 * */ public class DelDemo { public static void main(String[] args) { // 对hibernate.cfg.xml进行建模拿到sessionfactory工厂 Configuration configuration = new Configuration().configure("/hibernate.cfg.xml"); SessionFactory sessionFactory = configuration.buildSessionFactory(); // 通过工厂获取到session会话(操作数据库的) Session session = sessionFactory.openSession(); //获取事务对象 Transaction transaction=session.beginTransaction(); // 直接操作数据库 User user=new User(); user.setId(15); session.delete(user); //显示数据 List list = session.createQuery("from User").list(); for (Object object : list) { System.out.println(object); } //提交事务 transaction.commit(); // 关闭资源 session.close(); } }
效果如下: