java操作数据库的演进jdbc-datasource-hibernate-spring

java访问数据库最直接的方式便是JDBC,这里我们以Mysql数据库为例,来谈谈Java访问数据库上的演进,先建立一个数据库hib_test,然后建立一个用户表t_user,有三个字段,id,name,password:

1 create table `hib_test`.`t_user`(
2 `id` BIGINT not null auto_increment,
3 `name` VARCHAR(20) not null unique,
4 `password` VARCHAR(20) not null,
5 primary key (`id`)
6 );
7
8 create unique index `PRIMARY` on `hib_test`.`t_user`(`id`);
9 create unique index `name` on `hib_test`.`t_user`(`name`);

接着建立与表对应的域对象TUser:

1 package org.fn.dao;
2
3  /**
4 * TUser entity. @author MyEclipse Persistence Tools
5 */
6
7  public class TUser implements java.io.Serializable {
8
9 // Fields
10  
11 /**
12 *
13 */
14 private static final long serialVersionUID = 1L;
15 private Long id;
16 private String name;
17 private String password;
18
19 // Constructors
20  
21 /** default constructor */
22 public TUser() {
23 }
24
25 /** full constructor */
26 public TUser(String name, String password) {
27 this.name = name;
28 this.password = password;
29 }
30
31 // Property accessors
32
33 public Long getId() {
34 return this.id;
35 }
36
37 public void setId(Long id) {
38 this.id = id;
39 }
40
41 public String getName() {
42 return this.name;
43 }
44
45 public void setName(String name) {
46 this.name = name;
47 }
48
49 public String getPassword() {
50 return this.password;
51 }
52
53 public void setPassword(String password) {
54 this.password = password;
55 }
56
57 }

这要的操作便是insert和select

1.jdbc带c3p0数据源操作

1 package org.fn;
2
3 import java.beans.PropertyVetoException;
4 import java.sql.Connection;
5 import java.sql.PreparedStatement;
6 import java.sql.ResultSet;
7 import java.sql.SQLException;
8
9 import javax.sql.DataSource;
10
11 import com.mchange.v2.c3p0.ComboPooledDataSource;
12
13 public class DataSourceTest {
14
15 /**
16 * @param args
17 * @throws PropertyVetoException
18 * @throws SQLException
19 */
20 public static void main(String[] args) throws PropertyVetoException, SQLException {
21 // TODO Auto-generated method stub
22 ComboPooledDataSource cpds = new ComboPooledDataSource();
23 cpds.setDriverClass("com.mysql.jdbc.Driver" ); //loads the jdbc driver
24 cpds.setJdbcUrl("jdbc:mysql://localhost:3306/hib_test" );
25 cpds.setUser("root");
26 cpds.setPassword("root");
27
28 DataSource dataSource = cpds;
29
30 Connection conn = dataSource.getConnection();
31 PreparedStatement pstmt = conn.prepareStatement("select id, name, password from t_user");
32 ResultSet rs = pstmt.executeQuery();
33 while (rs.next()) {
34 System.out.println(rs.getLong(1) + " : " + rs.getString(2) + " : " + rs.getString(3));
35
36 }
37 rs.close();
38 pstmt.close();
39 conn.close();
40 }
41
42 }

2.hibernate数据库操作,其中两个配置文件如下:

TUser.hbm.xml:

1 <?xml version="1.0" encoding="utf-8"?>
2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
4 <!--
5 Mapping file autogenerated by MyEclipse Persistence Tools
6 -->
7 <hibernate-mapping>
8 <class name="org.fn.dao.TUser" table="t_user" catalog="hib_test">
9 <id name="id" type="java.lang.Long">
10 <column name="id" />
11 <generator class="native" />
12 </id>
13 <property name="name" type="java.lang.String">
14 <column name="name" length="20" not-null="true" unique="true" />
15 </property>
16 <property name="password" type="java.lang.String">
17 <column name="password" length="20" not-null="true" />
18 </property>
19 </class>
20 </hibernate-mapping>

hibernate.cfg.xml:

1 <?xml version='1.0' encoding='UTF-8'?>
2 <!DOCTYPE hibernate-configuration PUBLIC
3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
4 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
5
6 <!-- Generated by MyEclipse Hibernate Tools. -->
7 <hibernate-configuration>
8
9 <session-factory>
10 <property name="dialect">
11 org.hibernate.dialect.MySQLDialect
12 </property>
13 <property name="connection.url">
14 jdbc:mysql://localhost:3306/hib_test
15 </property>
16 <property name="connection.username">root</property>
17 <property name="connection.password">root</property>
18 <property name="connection.driver_class">
19 com.mysql.jdbc.Driver
20 </property>
21 <property name="show_sql">true</property>
22 <property name="format_sql">true</property>
23 <property name="c3p0.min_size">1</property>
24 <mapping resource="org/fn/dao/TUser.hbm.xml" />
25
26 </session-factory>
27
28 </hibernate-configuration>
1 package org.fn;
2
3 import java.util.List;
4
5 import hibernate.HibernateSessionFactory;
6
7 import org.fn.dao.TUser;
8 import org.hibernate.Query;
9 import org.hibernate.Session;
10 import org.hibernate.Transaction;
11
12 public class TUserOp {
13
14 public static void main(String[] args) {
15 //save();
16 find();
17 }
18
19 /**
20 *
21 */
22 public static void find() {
23 Session session = HibernateSessionFactory.getSession();
24 Transaction tx = session.beginTransaction();
25
26 Query query = session.createQuery("from TUser");
27 List<TUser> list = query.list();
28
29 for (TUser user : list) {
30 System.out.println(user.getId() + " : " + user.getName() + " : " + user.getPassword());
31 }
32
33 tx.commit();
34 session.close();
35 }
36
37 public static void save() {
38 Session session = HibernateSessionFactory.getSession();
39 Transaction tx = session.beginTransaction();
40
41 TUser user = new TUser();
42 user.setName("fnszb7");
43 user.setPassword("1234");
44
45 Long id = (Long) session.save(user);
46 System.out.println(id);
47
48 user.setPassword("4321");
49
50 tx.commit();
51 session.close();
52 }
53 }

3。通过spring的bean容器,和HibernateDaoSupport 与 HibernateTemplate操作数据库,配置文件如下:

applicationContext.xml:

1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
5
6
7 <bean id="sessionFactory"
8 class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
9 <!--
10 <property name="configLocation" value="file:src/hibernate.cfg.xml">
11 -->
12 <property name="configLocation" value="hibernate.cfg.xml">
13 </property>
14 </bean>
15 </beans>

 UserDao(进程HibernateDaoSupport):

1 package org.fn;
2
3 import java.util.List;
4
5 import org.hibernate.SessionFactory;
6 import org.springframework.context.ApplicationContext;
7 import org.springframework.context.support.ClassPathXmlApplicationContext;
8 import org.springframework.orm.hibernate3.HibernateTemplate;
9 import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
10
11 public class UserDao extends HibernateDaoSupport {
12 public List find(String queryString) {
13 ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
14 SessionFactory sf = (SessionFactory) ctx.getBean("sessionFactory");
15 super.setSessionFactory(sf);
16 HibernateTemplate ht = super.getHibernateTemplate();
17 return ht.find(queryString);
18 }
19 }
1 package org.fn;
2
3 import java.util.List;
4
5 import org.fn.dao.TUser;
6
7 public class SpringOp {
8
9 /**
10 * @param args
11 */
12 public static void main(String[] args) {
13 // TODO Auto-generated method stub
14 // ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
15 // SessionFactory sf = (SessionFactory) ctx.getBean("sessionFactory");
16
17 // HibernateTemplate ht = new HibernateTemplate(sf);
18 UserDao userDao = new UserDao();
19 List<TUser> list = userDao.find("from TUser");
20
21 for (TUser user : list) {
22 System.out.println(user.getId() + " : " + user.getName() + " : " + user.getPassword());
23 }
24 }
25
26 }
posted @ 2011-05-04 20:30  F.N.  阅读(1330)  评论(0编辑  收藏  举报