在Tomcat 5.5.4中通過Hibernate 2.1.8訪問MySQL數據庫

mysql> select * from users;

 

+----+-------+------------+----------------+
| id | name  | password   | createTime     |
+----+-------+------------+----------------+
|  1 | bitan | bbbbbbbbb  | 20050202035511 |
|  2 | helen | hhhhhhhhh  | 20050202035526 |
|  3 | susan | ssssssssss | 20050202035541 |
+----+-------+------------+----------------+
3 rows in set (0.00 sec)

 

K:/tomcat/conf/server.xml

……

<Context path="/test26" docBase="K:/test26" workDir="K:/test26/j2src" reloadable="true" debug="0">
        
    
<Resource name="jdbc/mydata" auth="Container" type="javax.sql.DataSource"
        maxActive="100" maxIdle="30" maxWait="10000"
        username="root" password="" driverClassName="com.mysql.jdbc.Driver"
        url="jdbc:mysql://localhost/mydata"/>

 

</Context>

</Host>

</Engine>

</Service>

</Server>

 

 

K:/test26/WEB-INF/web.xml

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns="
http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
    

    <!--與server.xml中的相關內容相互印證-->
    <resource-ref>
        <description>aaaaaaaaaaaaaaaa</description>
        <res-ref-name>jdbc/mydata</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>
   
   
</web-app>

K:/test26/WEB-INF/classes/hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC '-//Hibernate/Hibernate Configuration DTD//EN' 'http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd'>

<hibernate-configuration>
    <session-factory>

        <!--JNDI名字在web.xml和server.xml中設置-->
        <property name="connection.datasource">java:comp/env/jdbc/mydata</property>
        <property name="show_sql">false</property>
        <property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property>
       
        <mapping resource="Users.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

 

 

K:/test26/WEB-INF/classes/Users.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC '-//Hibernate/Hibernate Mapping DTD//EN' 'http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd'>

<hibernate-mapping>
    <class name="beans.Users" table="users">
        <id name="id" column="id" unsaved-value="0">
            <generator class="increment"/>
        </id>
        <property name="name" type="string">
            <column name="name" sql-type="varchar(20)" not-null="true"/>
        </property>
        <property name="password">
            <column name="password" sql-type="varchar(40)" not-null="true"/>
        </property>
        <property name="createTime">
            <column name="createTime" sql-type="timestamp" not-null="false"/>
        </property>
    </class>
</hibernate-mapping>

 

 

 

K:/test26/src/Users.java

//類似javaBean

package beans;

public class Users {
    private int id;
    private String name;
    private String password;
    private String createTime;
    public void setId(int id) {
        this.id = id;  
    }  
    public int getId() {
        return this.id;  
    }
    public void setName(String name) {
        this.name = name;  
    }
    public String getName() {
        return this.name;  
    }
    public void setPassword(String password) {
        this.password = password;  
    }
    public String getPassword() {
        return this.password;  
    }
    public void setCreateTime(String createTime) {
        this.createTime = createTime;  
    }
    public String getCreateTime() {
        return this.createTime;  
    }
}

 

 

K:/test26/src/HibernateUtil.java

//設置Hibernate

package utils;

import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;

public class HibernateUtil {
    private static final ThreadLocal sessions = new ThreadLocal();
    private static final SessionFactory factory;
    static {
        try {
            factory = new Configuration().configure().buildSessionFactory();
        } catch (HibernateException he) {
            he.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace(); 
        } 
    } 
    public static Session currentSession() throws HibernateException {
        Session s = (Session) sessions.get();
        if (s == null) {
            s = factory.openSession();
            sessions.set(s);  
        }  
        return s;
    }
    public static void closeSession() throws HibernateException {
        Session s = (Session) sessions.get();
        sessions.set(null); 
        if (s != null) {
            s.close(); 
        } 
    }
}

 

 

K:/test26/hiber.jsp

<%@ page contentType="text/html;charset=GBK"%>
<%@ page import="net.sf.hibernate.*,
                 net.sf.hibernate.cfg.*,

                 beans.Users,
                 utils.HibernateUtil,
                 java.util.Iterator"
%>
<%
try {
    net.sf.hibernate.Session h_session = utils.HibernateUtil.currentSession();
    

    //插入一行記錄
    Transaction tx = h_session.beginTransaction();
    Users users = new Users();
    users.setName("Jodan");
    users.setPassword("jjjjjjjjjjj");
    h_session.save(users);
    tx.commit();
    HibernateUtil.closeSession();
    

    //查詢所有記錄
    h_session = HibernateUtil.currentSession();
    Transaction tx2 = h_session.beginTransaction();
    Query query = h_session.createQuery("select U from beans.Users as U"); //Hibernate特有的SQL語法
    for (Iterator it = query.iterate(); it.hasNext();) {
        Users localUsers = (Users)it.next();
        int id = localUsers.getId();
        String name = localUsers.getName();
        String password = localUsers.getPassword();
        String createTime = localUsers.getCreateTime();
        out.println("id=" + id + " name=" + name + " password=" + password + " createTime=" + createTime + "<br>");
       
    }
    tx2.commit();
} catch (HibernateException he) {
    System.out.println("**********************" + he.getMessage());
    he.printStackTrace(); 
}   

%>

 

 

結果:

http://localhost:2000/test26/hiber.jsp

 

id=1 name=bitan password=bbbbbbbbb createTime=20050202035511
id=2 name=helen password=hhhhhhhhh createTime=20050202035526
id=3 name=susan password=ssssssssss createTime=20050202035541
id=4 name=Jodan password=jjjjjjjjjjj createTime=20050202045004

 

mysql> select * from users
    -> ;
+----+-------+-------------+----------------+
| id | name  | password    | createTime     |
+----+-------+-------------+----------------+
|  1 | bitan | bbbbbbbbb   | 20050202035511 |
|  2 | helen | hhhhhhhhh   | 20050202035526 |
|  3 | susan | ssssssssss  | 20050202035541 |
|  4 | Jodan | jjjjjjjjjjj | 20050202045004 |
+----+-------+-------------+----------------+
4 rows in set (0.06 sec)

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章