四、搭配hibernate
1. 在src下建立以下包
1.com.test.dao
2.com.test.imp
3.com.test.pojo
4.com.test.servicedao
5.com.test.servicedaoimp
6.com.test.util
7.com.test.exception
2. 在pojo中建user類,實作Serializable接口
3. 在dao中寫接口 interface userdao 加入方法,validate()方法
4. 在imp中寫userim實作userdao并實作其方法
5. 在pojo中建立User.hbm.xml
//Hibernate/Hibernate Mapping DTD 3.0//EN\" \"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd\" >
<hibernate-mapping package=\"com.test.pojo\">
<class name=\"User\" table=\"users\" >
<id name=\"usersId\" type=\"long\">
<column name=\"usersId\"></column>
<generator class=\"increment\"></generator>
</id>
<property name=\"usersName\" type=\"string\">
<column name=\"usersName\"></column>
</property>
<property name=\"usersPw\" type=\"string\">
<column name=\"usersPw\"></column>
</property>
</class>
</hibernate-mapping>
6、測試hibernate
(1)在util包下建HibernateUtils.java
package com.test.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtils {
private static SessionFactory factory;
static {
try {
Configuration cfg = new Configuration().configure();
factory = cfg.buildSessionFactory();
}catch(Exception e) {
e.printStackTrace();
}
}
public static SessionFactory getSessionFactory() {
return factory;
public static Session getSession() {
return factory.openSession();
public static void closeSession(Session session) {
if (session != null) {
if (session.isOpen()) {
session.close();
}
}
(1)在util包下建ExportDB .java
package com.test.util;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
public class ExportDB {
public static void main(String[] args) {
//讀取hibernate.cfg.xml檔案
Configuration cfg = new Configuration().configure();
SchemaExport export = new SchemaExport(cfg);
export.create(true, true);
}
}
(3) 建hibernate.cfg.xml
//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.driver_class\">com.mysql.jdbc.Driver</property>
<property name=\"connection.url\">jdbc:mysql://localhost:3306/b2c2</property>
<property name=\"dialect\">org.hibernate.dialect.MySQLDialect</property>
<property name=\"myeclipse.connection.profile\">mysql</property>
<property name=\"connection.username\">root</property>
<property name=\"connection.password\">root</property>
<property name=\"show_sql\">true</property>
<mapping resource=\"com/test/pojo/Privilege.hbm.xml\" />
<mapping resource=\"com/test/pojo/Role.hbm.xml\" />
<mapping resource=\"com/test/pojo/User.hbm.xml\" />
</session-factory>
</hibernate-configuration>
(4) 可以在util裡寫一Main方法對hibernate進行測試