业余时间学习下Hibernate.....
Hibernate的概念和作用就不废话了..百度都有..
Hibernate和JDBC比较:
使用JDBC有以下缺点:
1.需要编写大量的SQL语句
2.需要大量的?参数赋值
3.需要将ResultSet结果集合转换成实体对象
4.SQL中包含特有函数,无法移植
使用Hibernate可以解决以上问题:
1.自动生成SQL
2.自动给?赋值
3.自动将ResultSet结果集转换为实体对象
4.采用一致的方法对数据库操作,移植性好
Hibernate和MyBatis比较:
共性:
1.对JDBC进行了封装
2.采用ORM框架思想解决了Entity和数据库的映射问题
MyBatis:
1.MyBaits采用SQL与Entity映射,对JDBC封装程度较轻
2.MyBatis自己写SQL,更具有灵活性
Hibernate:
1.Hibernate采用数据库与Entity映射,对JDBC封装比较重.
2.Hibernate自动生成SQL,对于基本的操作,开发效率较高.
ORM思想:
ORM:Object Relation Mapping ,即对象关系映射,指的是Java对象与关系数据库之间的映射
ORM思想:就是将对象与数据库数据进行相互转换的思想,不同的框架技术实现ORM的手段不同,但更多的采用配置+反射的方式来实现ORM
创建工程和引JAR包什么的就不废话了...
具体的流程...
1.创建实体类
2.提供User.hbm.xml文件
3.将User.hbm.xml文件加入到hibernate.cfg.xml文件中
4.编写工具类ExportDB.java,将hbm生成ddl,也就是hbm2ddl
5.建立客户端类Client,添加用户数据到mySQL
先来一个结构图吧
好了..下面上代码
首先是实体类..
package com.hibernate.entity; import java.util.Date; public class Students { private int sid; private String sname; private String gender; private Date birthday; private String address; public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Students [sid=" + sid + ", sname=" + sname + ", gender=" + gender + ", birthday=" + birthday + ", address=" + address + "]"; } public Students(int sid, String sname, String gender, Date birthday, String address) { // super(); this.sid = sid; this.sname = sname; this.gender = gender; this.birthday = birthday; this.address = address; } public Students() { // super(); } }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="connection.username">root</property> <!-- 数据库用户名 --> <property name="connection.password">1234</property> <!-- 数据库密码 --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property><!-- 数据库驱动 --> <!-- 数据库地址 --> <property name="connection.url">jdbc:mysql://localhost:3306/test?user=root&password=1234&useUnicode=true&characterEncoding=UTF-8</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property><!-- mysql 数据库方言 --> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="hbm2ddl.auto">create</property> <mapping resource="com/hibernate/entity/Students.hbm.xml"/> </session-factory> </hibernate-configuration>
关于映射文件...我用的是Eclipse,安装了hibernate插件以后,自动生成的...
(话说新版的Eclipse启动的图片挺好看的...)
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated 2015-12-19 23:24:01 by Hibernate Tools 3.4.0.CR1 --> <hibernate-mapping> <class name="com.hibernate.entity.Students" table="STUDENTS"> <id name="sid" type="int"> <column name="SID" /> <generator class="assigned" /> </id> <property name="sname" type="java.lang.String"> <column name="SNAME" /> </property> <property name="gender" type="java.lang.String"> <column name="GENDER" /> </property> <property name="birthday" type="java.util.Date"> <column name="BIRTHDAY" /> </property> <property name="address" type="java.lang.String"> <column name="ADDRESS" /> </property> </class> </hibernate-mapping>
然后写一个测试方法 StudentsTest
package com.test; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.hibernate.entity.Students; //测试类 public class StudentsTest { private SessionFactory sessionFactory; private Session session; private Transaction transaction; @Before //初始化 public void init(){ //创建配置对象 Configuration config = new Configuration().configure(); //创建服务注册对象 ServiceRegistry serviceRegistry = (ServiceRegistry) new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); //创建会话工厂对象 sessionFactory = config.buildSessionFactory(serviceRegistry); //创建会话对象 session = sessionFactory.openSession(); //开启事务 transaction = session.beginTransaction(); } @After //释放资源 public void destory(){ transaction.commit(); //提交 session.close(); //关闭会话 sessionFactory.close(); //关闭会话工厂 } @Test public void testSaveStudents(){ try{ Students st = new Students(); st.setSid(1); st.setSname("小王"); st.setGender("男"); st.setBirthday(new Date()); st.setAddress("中南海"); session.save(st); }catch(Exception e){ e.printStackTrace(); } } }
因为数据库字符集问题...数据库的图片我就不传了..都是乱码...
关于hibernate.cfg.xml的配置,以后再说...
这个是根据慕课网学习后写出来的例子...感谢慕课网...
更新于2015-12-24
完整的hibernate单表增删查改
entity实体类
package com.hibernate.entity; import java.sql.Date; import java.sql.Timestamp; public class Emp { private Integer id; private String name; private Integer age; private Double salary; private Boolean marry; private Date birthday; private Timestamp lastLoginTime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Double getSalary() { return salary; } public void setSalary(Double salary) { this.salary = salary; } public Boolean getMarry() { return marry; } public void setMarry(Boolean marry) { this.marry = marry; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public Timestamp getLastLoginTime() { return lastLoginTime; } public void setLastLoginTime(Timestamp lastLoginTime) { this.lastLoginTime = lastLoginTime; } @Override public String toString() { return "Emp [id=" + id + ", name=" + name + ", age=" + age + ", salary=" + salary + ", marry=" + marry + ", birthday=" + birthday + ", lastLoginTime=" + lastLoginTime + "]"; } public Emp(Integer id, String name, Integer age, Double salary, Boolean marry, Date birthday, Timestamp lastLoginTime) { // super(); this.id = id; this.name = name; this.age = age; this.salary = salary; this.marry = marry; this.birthday = birthday; this.lastLoginTime = lastLoginTime; } public Emp() { // super(); } }
实体类配置文件
<?xml version="1.0"?> <!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="com.hibernate.entity.Emp" table="emp"> <!-- 配置实体类 和 表的关系 --> <id name="id" type="integer" column="id"> <!-- 配置主键属性和字段的关系 --> <generator class="sequence"> <!-- 用来指明主键的生成方式 --> <param name="sequence">emp_seq</param> <!-- 指定用于生成主键的sequence --> </generator> </id> <property name="name" type="string" column="name"></property> <property name="age" type="integer" column="age"></property> <property name="salary" type="double" column="salary"></property> <property name="birthday" type="date" column="birthday"></property> <property name="lastLoginTime" type="timestamp" column="last_Login_Time"></property> <property name="marry" type="yes_no" column="marry"></property> </class> </hibernate-mapping>
<!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 > <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property> <!-- 数据库地址 --> <property name="connection.username">Simba</property> <!-- 数据库用户名 --> <property name="connection.password">Simba</property> <!-- 数据库密码 --> <property name="connection.driver_class">oracle.jdbc.OracleDriver</property> <!-- 数据库驱动 --> <property name="dialect">org.hibernate.dialect.OracleDialect</property> <!-- mysql 数据库方言 --> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="hbm2ddl.auto">update</property> <mapping resource="com/hibernate/entity/Emp.hbm.xml"/> </session-factory> </hibernate-configuration>
<!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 > <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property> <!-- 数据库地址 --> <property name="connection.username">Simba</property> <!-- 数据库用户名 --> <property name="connection.password">Simba</property> <!-- 数据库密码 --> <property name="connection.driver_class">oracle.jdbc.OracleDriver</property> <!-- 数据库驱动 --> <property name="dialect">org.hibernate.dialect.OracleDialect</property> <!-- mysql 数据库方言 --> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="hbm2ddl.auto">update</property> <mapping resource="com/hibernate/entity/Emp.hbm.xml"/> </session-factory> </hibernate-configuration>
package com.hibernate.util; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; public class HibernateUtil { private static SessionFactory sessionFactory; //加载Hibernate主配置 static { //创建配置对象 Configuration config = new Configuration().configure(); //创建服务注册对象 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); //创建会话工厂对象 sessionFactory = config.buildSessionFactory(serviceRegistry); } //获取session public static Session getSession(){ return sessionFactory.openSession(); } }
package com.hibernate.test; import java.sql.Date; import java.sql.Timestamp; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import org.junit.Test; import com.hibernate.entity.Emp; import com.hibernate.util.HibernateUtil; public class EmpTest { private Session session; private HibernateUtil hibernateUtil; /** * 添加 * @throws Exception */ @Test public void add() throws Exception { Emp emp = new Emp(); emp.setName("小王"); emp.setAge(18); emp.setMarry(false); emp.setSalary(8000.0); emp.setBirthday(Date.valueOf("1993-1-1")); emp.setLastLoginTime(new Timestamp(System.currentTimeMillis())); session = hibernateUtil.getSession(); // 开启事务 Transaction transaction = (Transaction) session.beginTransaction(); try { session.save(emp); transaction.commit(); } catch (Exception e) { e.printStackTrace(); transaction.rollback(); } finally { session.close(); } } /** * 根据ID查找 */ @Test public void findById() { session = hibernateUtil.getSession(); Emp emp = (Emp) session.get(Emp.class, 1); System.out.println(emp.getName() + " " + emp.getAge()); session.close(); } /** * 修改更新 */ @Test public void update() { session = hibernateUtil.getSession(); Transaction transaction = session.beginTransaction(); Emp emp = (Emp) session.get(Emp.class, 1); try { emp.setName("大王"); emp.setAge(99); session.update(emp); transaction.commit(); } catch (Exception e) { e.printStackTrace(); transaction.rollback(); } finally { if (session != null) { session.close(); } } } /** * 删除 */ @Test public void delete(){ session = hibernateUtil.getSession(); Transaction transaction = session.beginTransaction(); Emp emp = (Emp)session.get(Emp.class, 2); try{ session.delete(emp); transaction.commit(); }catch(Exception e){ e.printStackTrace(); transaction.rollback(); }finally{ session.close(); } } /** * 查询所有 */ @Test public void findAll(){ session = hibernateUtil.getSession(); String hsql = "from Emp"; Query query = session.createQuery(hsql); List<Emp> listEmp = query.list(); for (Emp emp : listEmp) { System.out.println(emp.getName()); } session.close(); } }