Hibernate List集合

1.新建一個maven項目HibernateDemo

2.編寫pom.xml文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.meterbox</groupId>
	<artifactId>HibernateDemo</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>HibernateDemo Maven Webapp</name>
	<url>http://maven.apache.org</url>

	<!-- 屬性配置 -->
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<log4j.version>1.2.17</log4j.version>
		<mysql.version>5.1.30</mysql.version>
	</properties>

	<dependencies>


		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>


		<!-- 添加Hibernate依賴 -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>3.6.10.Final</version>
		</dependency>


		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${mysql.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.6.1</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-nop</artifactId>
			<version>1.6.4</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.7.2</version>
		</dependency>

		<!-- 添加javassist -->
		<dependency>
			<groupId>javassist</groupId>
			<artifactId>javassist</artifactId>
			<version>3.11.0.GA</version>
		</dependency>
		<!-- jsp頁面的jar -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.0.1</version>
		</dependency>
		<!-- 日誌 -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j.version}</version>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.2</version>
		</dependency>

	</dependencies>
	<build>
		<finalName>HibernateDemo</finalName>
	</build>
</project>

3.編寫Person類

public class Person {

	private String id;
	private String name;
	private int age;
	private List<String> schools = new ArrayList<String>();
//getter setter方法。。。。
	}

4.編寫Person.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="cn.edu.hpu.collection.model">
	<class name="Person" table="table_person">
		<id name="id" type="java.lang.String">
			<generator class="uuid" />
		</id>
		<property name="name" type="java.lang.String">
		</property>
		<property name="age" type="java.lang.Integer">
		</property>
		<list name="schools" table="table_schools">
			<!-- 外鍵 -->
			<key column="personid" not-null="true"></key>
			<!-- 映射集合屬性數據表的集合索引列 -->
			<list-index column="list_order" />
			<element type="string" column="school_name"></element>
		</list>
	</class>
</hibernate-mapping>

5.編寫hibernate.cfg.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<property name="connection.driver_class">
			com.mysql.jdbc.Driver
		</property>
		<property name="connection.url">jdbc:mysql://localhost:3306/zhjdata?useUnicode=true&characterEncoding=UTF-8</property>
		<property name="connection.username">root</property>
		<property name="connection.password">123456</property>
		<!-- 顯示SQL語句 -->
		<property name="show_sql">true</property>
		<property name="format_sql">true</property>
		
		<!-- 根據需要自動創建數據庫 -->
		<property name="hbm2ddl.auto">update</property>
		
		<!-- 定義方言 -->
		<property name="dialect">
			org.hibernate.dialect.MySQL5Dialect
		</property>

        <!-- 指定連接池裏最大連接數 -->
		<property name="hibernate.c3p0.max_size">20</property>
		<!-- 指定連接池裏最小連接數 -->
		<property name="hibernate.c3p0.min_size">1</property>
		<!-- 指定連接池裏連接的超時時長 -->
		<property name="hibernate.c3p0.timeout">5000</property>
		
        <!-- 指定連接池裏最大緩存多少個Statement對象 -->
		<property name="hibernate.c3p0.max_statements">100</property>
		<property name="hibernate.c3p0.idle_test_period">3000</property>
		<property name="hibernate.c3p0.acquire_increment">2</property>
		<property name="hibernate.c3p0.validate">true</property>
        
        <mapping resource="cn/edu/hpu/collection/model/Person.hbm.xml"/>
	</session-factory>
</hibernate-configuration>

6.編寫HibernateUtil類

package cn.edu.hpu.util;


import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

	/** ThreadLocal Session Map */
	public static final ThreadLocal<Session> SESSIONMAP = new ThreadLocal<Session>();
	private static final SessionFactory sessionFactory;
	private static final Logger LOGGER = Logger.getLogger("appender2");
	static {
		try {
			LOGGER.debug("HibernateUti.static - loading cofig");
			sessionFactory = new Configuration().configure("hibernate.cfg.xml")
					.buildSessionFactory();
			LOGGER.debug("HibernateUtil.static - end");
		} catch (Throwable ex) {
			ex.printStackTrace();
			LOGGER.error("HibernateUti error : ExceptionInInitializerError");
			throw new ExceptionInInitializerError(ex);
		}
	}

	private HibernateUtil() {

	}

	public static Session getSession() throws HibernateException {
		Session session = SESSIONMAP.get();

		if (session == null) {
			session = sessionFactory.openSession();
			SESSIONMAP.set(session);
		}

		return session;
	}

	public static void closeSession() throws HibernateException {
		Session session = SESSIONMAP.get();
		SESSIONMAP.set(null);

		if (session != null) {
			session.close();
		}
	}
}
7.配置日誌文件log4j.properties

# 1.\u6587\u672C\u683C\u5F0F
# set level  
log4j.rootLogger=debug,appender2  
# output into file
log4j.appender.appender2=org.apache.log4j.FileAppender  
# file direct
# text file
log4j.appender.appender2.File=D:/data/logs/Log4JDemo02.log  
# output style
log4j.appender.appender2.layout=org.apache.log4j.TTCCLayout  
8.編寫測試類PersonManger

package cn.edu.hpu.test;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import cn.edu.hpu.collection.model.Person;
import cn.edu.hpu.util.HibernateUtil;

public class PersonManger {

	@Test
	public void testSave() {
		Session session = HibernateUtil.getSession();
		Transaction trans = session.beginTransaction();
		Person p = new Person();
		p.setAge(29);
		p.setName("zhangHJ");
		List<String> schools = new ArrayList<String>();
		schools.add("小學");
		schools.add("中學");
		schools.add("大學");
		p.setSchools(schools);
		session.save(p);
		trans.commit();
		HibernateUtil.closeSession();

	}
}


10.結果顯示





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