简单的hibernate原生SQL TestDemo

(入门级demo)

开发环境:

Eclipse Standard/SDK

Version: Kepler Release
Build id: 20130614-0229

新建Java Project项目Test_HibSql_DemoApp

项目需要引入Hibernate Libraries(hibernate-distribution-3.6.10.Final-dist.tar.gz)
还需要引入mysql相关数据库jar包:mysql-connector-java-5.1.7-bin.jar

测试代码文件:TestDemoMain.java

package test;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.cfg.AnnotationConfiguration;

/**
 * @author
 * @createDate
 */
public class TestDemoMain {

	/**
	 * 
	 */
	public TestDemoMain() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @createDate
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		System.out.println("Test_HibSql_DemoApp...");

		Session session = new AnnotationConfiguration().configure().buildSessionFactory().openSession();

		List list = session.createSQLQuery("select a.id, a.name from test_demo_tba a").list();
		System.out.println("list.size=" + list.size());
		for (int i = 0; i < list.size(); ++i) {
			Object[] object = (Object[]) list.get(i);
			System.out.println("[" + i + "]:" + object[0] + "," + object[1]);
		}

		System.out.println("Test_HibSql_DemoApp ok.");
	}

}

配置文件:hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE hibernate-configuration PUBLIC  
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<property name="connection.url">jdbc:mysql://192.168.0.6:3306/test_db</property>
		<property name="connection.username">root</property>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="connection.password">12345</property>
		<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>

		<property name="current_session_context_class">thread</property>
		<property name="hibernate.show_sql">true</property>
	</session-factory>
</hibernate-configuration>


用到的表:

CREATE TABLE `test_demo_tba` (
  `id` bigint(20) NOT NULL auto_increment,
  `name` varchar(20) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

运行结果:

Test_HibSql_DemoApp...
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Hibernate: select a.id, a.name from test_demo_tba a
list.size=6
[0]:61,aaa
[1]:63,aaa
[2]:65,aaa
[3]:67,aaa
[4]:69,aaa
[5]:70,aaa
Test_HibSql_DemoApp ok.



你可能感兴趣的:(简单的hibernate原生SQL TestDemo)