Home php教程 php手册 在resin3.0中配置hibernate2.1.2连mysql

在resin3.0中配置hibernate2.1.2连mysql

Jun 13, 2016 am 10:06 AM
mysql exist Configuration

 

在resin3.0中配置hibernate2.1.2连mysql

在resin3.0中配置hibernate2.1.2连mysql

Author : hamal

约定:

resin3 代表resin3.0的安装根目录

hibernate2 代表hibernate2.1.2的安装根目录



1.        在resin3下建立我们的web应用根,如resin3mydomain目录(mydomain的目录名可以随意取,之后在配置文件中配置即可)

2.        在resin3mydomain目录下分别建立resin3mydomainWEB-INFclasses目录和resin3mydomainWEB-INFlib目录。
这两个目录对应本web应用程序上下文的类装载器搜索路径(对于jar来说是resin3mydomainWEB-INFlib,对于class文件来说是resin3mydomainWEB-INFclasses)。我们把这两个路径分别称为应用库类路径(用于存放和本应用相关的jar类库)和上下文类路径(用于存放本应用的class文件和xml配置文件)。
另外还有一个路径是resin3lib目录,我们称该路径为全局库类路径(存放于resin3服务器上,供该服务器上所有web应用共享使用的相关jar类库)。

3.        本示例使用的是mysql数据库,所以我们将mysql的jdbc驱动jar包(mm.mysql-2.0.4-bin.jar)放入resin3lib目录中,之后该驱动将能被所有web应用所用。

4.      将hibernate2 hibernate2.jar文件拷贝到resin3mydomainWEB-INFlib 目录下,然后拷贝hibernate2lib 目录下必须的jar文件也拷贝到resin3mydomainWEB-INFlib 目录下。如果你不是很清楚哪些包是你所需要的,可以参看hibernate2libREADME.txt文件,或者,再简单一点,我们将hibernate2lib 目录下的所有jar文件都拷贝到resin3mydomainWEB-INFlib 目录下。

5.      现在我们开始配置resin的jdbc数据库连接池。修改resin3confresin.conf文件

a)      搜索webapps,将webapps替换为我们自定义的应用目录mydomain。

b)      查找元素,取消该元素的注释状态,该文件的注释采用的是html风格的注释方式

c)      将元素修改为如下形式



      jdbc/mysql

      

        jdbc:mysql://192.162.125.3:3306/mysql

        root

        12345678

      


      8

      20

      30s

   


如此resin的jdbc连接池配置完成。

6.      将hibernate2src目录下的hibernate.properties、log4j.properties、oscache.properties文件拷贝到resin3 mydomainWEB-INFclasses目录下。

7.      由于我们使用的是mysql数据库,所以修改hibernate.properties文件中关于mysql部分的配置,并注释掉原默认的HypersonicSQL配置。注释配置就是在语句前加 # 符号。如:

#hibernate.dialect net.sf.hibernate.dialect.HSQLDialect



下面是一个典型的mysql配置:

hibernate.dialect net.sf.hibernate.dialect.MySQLDialect

hibernate.connection.driver_class org.gjt.mm.mysql.Driver

hibernate.connection.driver_class com.mysql.jdbc.Driver

hibernate.connection.url jdbc:mysql://192.162.125.3:3306/mydb

hibernate.connection.username root

hibernate.connection.password 12345678



我们需要修改的就是下面3行:

url是指jdbc连接描述符,格式为jdbc:mysql://数据库IP:端口号/数据库名

username是指用于登陆该数据库的用户名

password该用户密码



8.      将hibernate和resin的数据库连接池绑定。在目录里创建一个hibernate.cfg.xml文件,文件内容如下



br />
    PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"

    "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">



   

        java:comp/env/jdbc/mysql

        true

        net.sf.hibernate.dialect.MySQLDialect

        

        

   




元素告诉hibernate使用resin中定义的jndi来连接数据库, 子元素用于描述每一个映射数据库表的配置文件路径,

其声明了User.hbm.xml是一个Hibernate XML映射文件,对应持久化类User。这个文件包含了把POJO类映射到数据库表(或多个数据库表)的元数据。我们稍后就回来看这个文件。让我们先编写这个POJO类,再看声明它的映射元数据。

9.      在mysql中建立user表该表的格式如下:

User_id    Password    Nick_name    E_mail
1            6666          hamal           hamal@sohu.com
2            6666          vampire        vampire@sina.com
3            6666          ande            ande@yahoo.com

在resin3 mydomainWEB-INFclasses目录下分别新建3个java文件:Test.java、HibernateUtil.java、User.java。



HibernateUtil.java源代码如下:该类是一个辅助类,用于获得一个静态的SessionFactory,SessionFactory负责一个数据库,也只对应一个XML配置文件(hibernate.cfg.xml)。



import net.sf.hibernate.*;

import net.sf.hibernate.cfg.*;



public class HibernateUtil {



    private static final SessionFactory sessionFactory;



    static {

        try {

            sessionFactory = new Configuration().configure().buildSessionFactory();

        } catch (HibernateException ex) {

            throw new RuntimeException("Exception building SessionFactory: " + ex.getMessage(), ex);

        }

    }



    public static final ThreadLocal session = new ThreadLocal();



    public static Session currentSession() throws HibernateException {

        Session s = (Session) session.get();

        // Open a new Session, if this Thread has none yet

        if (s == null) {

            s = sessionFactory.openSession();

            session.set(s);

        }

        return s;

    }



    public static void closeSession() throws HibernateException {

        Session s = (Session) session.get();

        session.set(null);

        if (s != null)

            s.close();

    }

}



User.java 源代码如下:Hibernate让普通的Java对象(Plain Old Java Objects ,就是POJOs,有时候也称作Plain Ordinary Java Objects)变成持久化类。一个POJO很像JavaBean,属性通过getter和setter方法访问,对外隐藏了内部实现的细节。



public class User {



    private Integer id;

    private String nick;

    private String password ;

    private String email;



    public User() {

    }



    public Integer getId() {

        return id;

    }



    public void setId(Integer id) {

        this.id = id;

    }



    public String getNick() {

        return nick;

    }



    public void setNick(String nick) {

        this.nick = nick;

    }



    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;

    }



}



Test.java 源代码如下:



import javax.naming.*;

import net.sf.hibernate.*;

import java.util.*;



public class Test{

  void Test(){

   

  }

  public static void insert(){

    try{   

      Session hSession = HibernateUtil.currentSession();

      Transaction tx= hSession.beginTransaction();

      

      User newp = new User();

      Integer id = new Integer("4");

      newp.setId(id);

      newp.setNick("love");

      newp.setPassword("123");

      newp.setEmail("test@sohu.com");

      

      hSession.save(newp);

      tx.commit();

      HibernateUtil.closeSession();

    }catch(Exception e){

      e.printStackTrace();

    }

  }

}





10.  编写Hibernate XML映射文件

在resin3 mydomainWEB-INFclasses目录下新建User.hbm.xml文件,文件内容如下:





br />
    PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"

    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">







  

   

      

      

   




   

      

   




   

      

   




   

      

   


  








简单说明:

元素中的name属性代表的是User类的全路径名(即包名+类名的形式),table属性代表的是该User类映射的数据库表名。

元素代表该表的主键,name属性代表在User类中对应的类属性名。

元素代表该id属性对应的数据库user表中的user_id字段。





11.  界面测试:

我们在resin3mydomain目录下新建一个test.jsp文件如下:









This is a test!





This is a test!











12.  测试

好了,现在所有的准备工作都已经做完了,开始测试看看。

我们启动rensin服务器,启动文件为resin3binhttpd.exe,双击该文件即可。

在测试前我们看到的mysql中user表的内容如下。

User_id    Password    Nick_name    E_mail
1            6666          hamal           hamal@sohu.com
2            6666          vampire        vampire@sina.com
3            6666          ande            ande@yahoo.com

现在我们打开IE,在地址栏中输入http://localhost:8080/test.jsp

当界面上正常显示出This is a test!之后,我们再查看数据库内容如下:

User_id    Password    Nick_name    E_mail
1            6666          hamal           hamal@sohu.com
2            6666          vampire        vampire@sina.com
3            6666          ande            ande@yahoo.com
4            123            love            test@sohu.com


恭喜,你已经完成了本次示例!
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The relationship between mysql user and database The relationship between mysql user and database Apr 08, 2025 pm 07:15 PM

In MySQL database, the relationship between the user and the database is defined by permissions and tables. The user has a username and password to access the database. Permissions are granted through the GRANT command, while the table is created by the CREATE TABLE command. To establish a relationship between a user and a database, you need to create a database, create a user, and then grant permissions.

MySQL: The Ease of Data Management for Beginners MySQL: The Ease of Data Management for Beginners Apr 09, 2025 am 12:07 AM

MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.

Can I retrieve the database password in Navicat? Can I retrieve the database password in Navicat? Apr 08, 2025 pm 09:51 PM

Navicat itself does not store the database password, and can only retrieve the encrypted password. Solution: 1. Check the password manager; 2. Check Navicat's "Remember Password" function; 3. Reset the database password; 4. Contact the database administrator.

Query optimization in MySQL is essential for improving database performance, especially when dealing with large data sets Query optimization in MySQL is essential for improving database performance, especially when dealing with large data sets Apr 08, 2025 pm 07:12 PM

1. Use the correct index to speed up data retrieval by reducing the amount of data scanned select*frommployeeswherelast_name='smith'; if you look up a column of a table multiple times, create an index for that column. If you or your app needs data from multiple columns according to the criteria, create a composite index 2. Avoid select * only those required columns, if you select all unwanted columns, this will only consume more server memory and cause the server to slow down at high load or frequency times For example, your table contains columns such as created_at and updated_at and timestamps, and then avoid selecting * because they do not require inefficient query se

How to view mysql How to view mysql Apr 08, 2025 pm 07:21 PM

View the MySQL database with the following command: Connect to the server: mysql -u Username -p Password Run SHOW DATABASES; Command to get all existing databases Select database: USE database name; View table: SHOW TABLES; View table structure: DESCRIBE table name; View data: SELECT * FROM table name;

How to create navicat premium How to create navicat premium Apr 09, 2025 am 07:09 AM

Create a database using Navicat Premium: Connect to the database server and enter the connection parameters. Right-click on the server and select Create Database. Enter the name of the new database and the specified character set and collation. Connect to the new database and create the table in the Object Browser. Right-click on the table and select Insert Data to insert the data.

How to copy tables in mysql How to copy tables in mysql Apr 08, 2025 pm 07:24 PM

Copying a table in MySQL requires creating new tables, inserting data, setting foreign keys, copying indexes, triggers, stored procedures, and functions. The specific steps include: creating a new table with the same structure. Insert data from the original table into a new table. Set the same foreign key constraint (if the original table has one). Create the same index. Create the same trigger (if the original table has one). Create the same stored procedure or function (if the original table is used).

How to view database password in Navicat for MariaDB? How to view database password in Navicat for MariaDB? Apr 08, 2025 pm 09:18 PM

Navicat for MariaDB cannot view the database password directly because the password is stored in encrypted form. To ensure the database security, there are three ways to reset your password: reset your password through Navicat and set a complex password. View the configuration file (not recommended, high risk). Use system command line tools (not recommended, you need to be proficient in command line tools).

See all articles