本例将使用struts2和hiberante开发,首选将struts2相关的jar包复制到web 工程的WebRoot\WEB-INF\lib目录下。
所需的JAR包如下图,
然后将连接mysql数据库所需的驱动JAR包也同样复制到lib目录中
右击工程名 MyEclipse->Add Hibernate Capablities
弹出如下窗口,按如下勾选配置好,点击下一步
接下去的两步可以不配置,去年勾选,即不配置数据库连接与创建session工厂。
点击完成后,会在lib包上出现很多hibernate相关的JAR包
例子:下面尝试用hibernate将Person对象存入数据库中
hibernate.cfg.xml配置文件,用于配置数据库的相关连接信息
<?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"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property><!--hibernte为数据库名--> <property name="connection.username">root</property> <property name="connection.password">123456</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <mapping resource="Person.hbm.xml"></mapping> </session-factory> </hibernate-configuration>
HibernateUtil .java 用来获取session及关闭session
package com.hibernate.util; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static SessionFactory sessionFactory; static{ try{ sessionFactory = new Configuration().configure().buildSessionFactory(); }catch (Exception e) { e.printStackTrace(); } } public static Session currentSession(){ Session session = sessionFactory.openSession(); return session; } public static void closeSession(Session session){ session.close(); } }
Person.java
package com.hibernate.model; import java.sql.Date; public class Person { private Integer id; private String username; private String password; private Integer age; private Date registerdate; 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 getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Date getRegisterdate() { return registerdate; } public void setRegisterdate(Date sterregisterdatedate) { this.registerdate = sterregisterdatedate; } }
Person对象对应的配置文件,同样放在src目录下。
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.hibernate.model.Person" table="person"> <id name="id" column="id" type="int"> <generator class="increment"></generator><!-- 主键ID的生成方式 --> </id> <property name="username" column="username" type="java.lang.String"></property> <property name="password" column="password" type="java.lang.String"></property> <property name="age" column="age" type="int"></property> <property name="registerdate" column="registerdate" type="date"></property> </class> </hibernate-mapping>
Test.java 测试类
package com.hibernate.util; import java.sql.Date; import java.util.List; import com.hibernate.model.Person; import com.hibernate.persistence.DBPerson; public class Test { public static void main(String[] args) { //实例化一个person Person person = new Person(); person.setId(11); person.setAge(22); person.setPassword("1111"); person.setUsername("hp"); person.setRegisterdate(new Date(new java.util.Date().getTime())); DBPerson.save(person); //保存 //查找 List list = DBPerson.getAll(); for (int i = 0; i < list.size(); i++) { person = (Person) list.get(i); System.err.println(person.getId() + " " + person.getUsername() + " " + person.getPassword() + " " + person.getAge() + " " + person.getRegisterdate()); } } }
DBPerson.java 用于保存或查找person
package com.hibernate.persistence; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import com.hibernate.model.Person; import com.hibernate.util.HibernateUtil; public class DBPerson { //保存person public static void save(Person person) { Session session = HibernateUtil.currentSession(); Transaction tx = session.beginTransaction(); try { session.save(person); tx.commit(); } catch (Exception e) { System.out.println("新增用户失败"); if (null != tx) { tx.rollback(); } } finally { HibernateUtil.closeSession(session); } } //查找并返回所有person public static List getAll(){ Session session = HibernateUtil.currentSession(); Transaction tx = session.beginTransaction(); List list = null; try { Query query = session.createQuery(" from Person");//hql语句 list = query.list(); } catch (Exception e) { System.out.println("查询用户失败"); if (null != tx) { tx.rollback(); } } finally { HibernateUtil.closeSession(session); } return list; } public static Person getPersonById(Integer id){ Session session = HibernateUtil.currentSession(); Transaction tx = session.beginTransaction(); Person person = null; try { person = (Person) session.get(Person.class, id); } catch (Exception e) { System.out.println("查询用户失败"); if (null != tx) { tx.rollback(); } } finally { HibernateUtil.closeSession(session); } return person; } //删除 public static void deletePerson(Person person){ Session session = HibernateUtil.currentSession(); Transaction tx = session.beginTransaction(); try { session.delete(person); tx.commit(); } catch (Exception e) { System.out.println("删除用户失败"); if (null != tx) { tx.rollback(); } } finally { HibernateUtil.closeSession(session); } } //更新 public static void updatePerson(Person person){ Session session = HibernateUtil.currentSession(); Transaction tx = session.beginTransaction(); try { session.update(person); tx.commit(); } catch (Exception e) { System.out.println("更新用户失败"); e.printStackTrace(); if (null != tx) { tx.rollback(); } } finally { HibernateUtil.closeSession(session); } } }
最后在数据库中生成的纪录
例2:演示多种数据类型之间匹配。
Customers(客户),有如下属性
create table customers( id bigint not null primary key, name varchar(15) not null, email varchar(128) not null, password varchar(128) not null, phone int, address varchar(255), sex char(1), is_married bit, description text, image blob, birthday date, registered_time timestamp );
Customer.java
package com.hibernate.model; import java.sql.Date; import java.sql.Timestamp; public class Customer { private Long id; private String name; private String email; private String password; private int phone; private String address; private char sex; private boolean married; private String description; private byte[] image; //blob类型一般用数组来表示 private Date birthday; private Timestamp registeredTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getPhone() { return phone; } public void setPhone(int phone) { this.phone = phone; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public char getSex() { return sex; } public void setSex(char sex) { this.sex = sex; } public boolean isMarried() { return married; } public void setMarried(boolean married) { this.married = married; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public byte[] getImage() { return image; } public void setImage(byte[] image) { this.image = image; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public Timestamp getRegisteredTime() { return registeredTime; } public void setRegisteredTime(Timestamp registeredTime) { this.registeredTime = registeredTime; } }
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.hibernate.model.Customer" table="customers"> <id name="id" column="id" type="long"> <generator class="increment"></generator> </id> <property name="name" column="name" type="string" not-null="true"></property> <property name="email" column="email" type="string" not-null="true"></property> <property name="password" column="password" type="string" not-null="true"></property> <property name="phone" column="phone" type="int"></property> <property name="address" column="address" type="string"></property> <property name="sex" column="sex" type="character"></property> <property name="married" column="is_married" type="boolean"></property> <property name="description" column="description" type="text"></property> <property name="image" column="image" type="binary"></property> <property name="birthday" column="birthday" type="date"></property> <property name="registeredTime" column="registered_time" type="timestamp"></property> </class> </hibernate-mapping>