[标题]:MyEclipse环境下Hibernate入门实例
[时间]:2010-9-23
[摘要]:一个MyEclipse Hibernate demo。
[关键字]:Hibernate,入门,MyEclipse,demo,MySQL Connector/J
[环境]:MyEclipse8.6 ,Hibernate3.3,MySQL5.1
[作者]:http://blog.csdn.com/xw13106209
首先在MyEclipse下创建一个WebProject,项目命名为demo,然后【MyEclipse->project capablities->add hibernate capabilities】,跟着向导操作,最后会生成一个hibernate.cfg.xml和一个HibernateSessionFactory.java文件。在向导中要求填写一些数据库连接的配置信息以及HibernateSessionFactory存放的包,配置信息我们可以参考下面的hibernate.cfg.xml来填写,而HibernateSessionFactory我们放在com.demo.hibernate.util这个包里面。
package com.demo.hibernate.util;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {
/**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;
static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return session factory
*
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
}
<?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="dialect">org.hibernate.dialect.MySQLDialect</property>
<!--
<property name="show_sql">true</property>
-->
<!-- 连接字符串 -->
<property name="connection.url">jdbc:mysql://localhost:3306/demo</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- 数据库驱动 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 映射文件,是后来添加的,不是想到自动生成的 -->
<mapping resource="com/demo/hibernate/beans/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
在MySql中创建一个名为demo的数据库,然后将下面的代码另存为“*.sql”文件,再将该文件导入数据库。当然也可直接通过类似navicat的数据库UI来创建数据库。
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) DEFAULT NULL,
`password` varchar(50) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
我们知道Hibernate是用户将对象与数据库表进行映射,那么下面编写映射文件:User.hbm.xml(在com.demo.hibernate.beans包中),从代码中我们可以看到name与column属性,name表示User类中的属性,column表示数据库表user中的字段名称。类中的属性和表中的字段可以不相同,如果相同的话column可以省略。比如下面的column="username" 和column="password" 可以省略不写。像<property name="email" /> 一样。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
<hibernate-mapping package="com.demo.hibernate.beans">
-->
<hibernate-mapping>
<class name="com.demo.hibernate.beans.User" table="user">
<id name="id" column="ID" >
<generator class="native" />
</id>
<property name="username" column="username" />
<property name="password" column="password" />
<property name="email" />
</class>
</hibernate-mapping>
这里我们不一定要求User类中的属性与表user的字段相同,不过如果相同则可以省去一些步骤,就是前面提到的*.hbm.xml文件中的一些字段可以省略。
package com.demo.hibernate.beans;
public class User {
private int id;
private String username;
private String password;
private String email;
public int getId() {
return id;
}
public void setId(int 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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
DAO就是Database Access Objects,数据访问对象的英文缩写。顾名思义对数据库操作的方法都写在这个类中,就比如代码中getUser()方法就是需要读取数据库信息。不过hibernate因为通过映射的方法不直接使用SQL语句操纵数据库,而是引入了HQL语言。最明显的一点是:
Query query=session.createQuery("from User where username=?");
这里from User中的User是指User类而不是user表,HQL直接对对象操作。
package com.demo.hibernate.dao; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import com.demo.hibernate.beans.User; import com.demo.hibernate.util.HibernateSessionFactory; public class UserDAO { public User getUser(String username) throws HibernateException{ Session session=null; Transaction tx=null; User user=null; try { session=HibernateSessionFactory.getSession(); tx=session.beginTransaction(); Query query=session.createQuery("from User where username=?"); query.setString(0, username.trim()); user=(User)query.uniqueResult(); query=null; //session.save(user); tx.commit(); //session.close(); } // catch(HibernateException e) // { // throw e; // } // finally // { // if(tx!=null) // { // tx.rollback(); // } // HibernateSessionFactory.closeSession(); // } catch(HibernateException e) { System.out.println(e.getMessage()); e.printStackTrace(); } return user; } }
package com.demo.hibernate.service;
import com.demo.hibernate.beans.User;
import com.demo.hibernate.dao.UserDAO;
public class UserService {
public boolean valid(String username,String password)
{
UserDAO test=new UserDAO();
User user=test.getUser("admin");
if(user.getPassword().equals(password))
{
return true;
}
else
{
return false;
}
}
public static void main(String args[])
{
UserService service=new UserService();
boolean login=service.valid("admin", "admin");
System.out.println("验证结果"+login);
}
}
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
验证结果:true