hibernate连接mysql示范

今天用了一下java的数据库持久化-业务的hibernate框架。下面给出hibernate 连接mysql数据库示例

 

建表结构如下

 

mysql> desc test;
+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| id       | int(11)      | NO   | PRI | NULL    | auto_increment |
| username | varchar(100) | NO   |     | NULL    |                |
+----------+--------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql>

 

 

hibernate配置文件 hibernate.cfg.xml

 

true org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://192.168.25.152/test 这里写用户名 密码

 

表映射 user.hbm.xml

 

 

表映射类

 

package com; /** * Created by IntelliJ IDEA. * User: Administrator * Date: 2006-2-6 * Time: 22:10:05 * To change this template use File | Settings | File Templates. */ public class TestDb { private String username; private Long id; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String myname) { this.username = myname; } }

 

测试类

 

package com; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class test { //遍历 public static void all() { Query q = session.createQuery("select c.id,c.username from TestDb as c"); List l = q.list(); for(int i=0;i

 

文件结构

 

 

 

你可能感兴趣的:(Java,web技术)