hibernate中的一对多,一个用户对应多个频道
频道表:
CREATE TABLE `channel` ( `channelId` int(11) NOT NULL auto_increment, `channel` varchar(50) default NULL COMMENT '频道简称', `channel_name` varchar(60) default NULL COMMENT '频道全名', `userId` int(11) default NULL COMMENT '关联用户表的键', PRIMARY KEY (`channelId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='频道表'
用户表:
CREATE TABLE `user` ( `userId` int(11) NOT NULL auto_increment, `userName` varchar(32) NOT NULL default '', `password` varchar(32) NOT NULL default '', `name` varchar(50) default NULL COMMENT '用户名', `email` varchar(50) default NULL, `phone` varchar(20) default NULL, `phone1` varchar(20) default NULL COMMENT '备用电话', `phone2` varchar(20) default NULL COMMENT '备用电话', `authority` varchar(50) NOT NULL default 'ROLE_USER' COMMENT '用户权限代码', `actor` int(2) NOT NULL default '0' COMMENT '用户角色', `department` varchar(50) default NULL COMMENT '用户所属部门', PRIMARY KEY (`userId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8
1.一对多关联关系,使用集合来表示; 2.映射文件中使用<set>标签配置: <set name="集合名"> <key column="数据库中字段名" /> <one-to-many class="集合子元素类名"/> </set>
对应的配置文件:
Channel.hbm.xml文件:
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse - Hibernate Tools --> <hibernate-mapping> <class lazy="false" name="com.autonavi.monitor.model.Channel" table="channel"> <id name="channelId" type="integer" unsaved-value="0"> <column name="channelId"/> <generator class="native"/> </id> <property name="channel" type="string"> <column name="channel" /> </property> <property name="channelName" type="string"> <column name="channel_name"/> </property> </class> </hibernate-mapping>
User.hbm.xml文件:
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse - Hibernate Tools --> <hibernate-mapping> <class lazy="false" name="com.autonavi.monitor.model.User" table="user"> <id name="userId" type="integer" unsaved-value="0"> <column name="userId"/> <generator class="native"/> </id> <property name="name" type="string"> <column name="name" /> </property> <property name="userName" type="string"> <column name="userName" not-null="true"/> </property> <property name="password" type="string"> <column name="password" not-null="true"/> </property> <property name="actor" type="int"> <column name="actor"/> </property> <property name="authority" type="string"> <column name="authority"/> </property> <property name="email" type="string"> <column name="email"/> </property> <property name="phone" type="string"> <column name="phone"/> </property> <property name="phone1" type="string"> <column name="phone1"/> </property> <property name="phone2" type="string"> <column name="phone2"/> </property> <set name="channels"> <key column="userId" /> <one-to-many class="com.autonavi.monitor.model.Channel"/> </set> </class> </hibernate-mapping>
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"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <!-- property name="connection.datasource">java:comp/env/MysqlDB</property>--> <property name="show_sql">false</property> <property name="connection.release_mode">auto</property> <!-- cache --> <property name="hibernate.cache.provider_class"> org.hibernate.cache.EhCacheProvider </property> <property name="hibernate.cache.use_query_cache">true</property> <property name="cache.use_second_level_cache">true</property> <property name="query.factory_class"> org.hibernate.hql.classic.ClassicQueryTranslatorFactory </property> <!-- <property name="query.factory_class"> org.hibernate.hql.ast.ASTQueryTranslatorFactory </property> --> <property name="format_sql">true</property> <property name="use_sql_comments">true</property> <mapping resource="config/hibernate/monitor/User.hbm.xml" /> <mapping resource="config/hibernate/monitor/Channel.hbm.xml" /> </session-factory> </hibernate-configuration>
对应的Model:
package com.autonavi.monitor.model; import com.autonavi.core.model.BaseModel; public class Channel extends BaseModel { /** * */ private static final long serialVersionUID = 1L; /** * 频道主键Id */ private Integer channelId; /** * 频道简称 */ private String channel; /** * 频道全名 */ private String channelName; public Channel() {} public Channel(Integer channelId, String channel, String channelName) { super(); this.channelId = channelId; this.channel = channel; this.channelName = channelName; } public Integer getChannelId() { return channelId; } public void setChannelId(Integer channelId) { this.channelId = channelId; } public String getChannel() { return channel; } public void setChannel(String channel) { this.channel = channel; } public String getChannelName() { return channelName; } public void setChannelName(String channelName) { this.channelName = channelName; } }
package com.autonavi.monitor.model; import java.util.Set; import com.autonavi.core.model.BaseModel; public class User extends BaseModel { /** * */ private static final long serialVersionUID = 1L; private Integer userId; private String userName; private String password; private String name; private String department; private String email; private String phone; private String phone1; private String phone2; private int actor; private String authority; // 0 删除 1未删除 private int status; private Set<Channel> channels; public User() {} public User(Integer userId, String userName, String password, String name, String email, String phone, String phone1, String phone2, String department, int actor, String authority, Set<Channel> channels) { super(); this.userId = userId; this.userName = userName; this.password = password; this.name = name; this.email = email; this.phone = phone; this.phone1 = phone1; this.phone2 = phone2; this.department = department; this.actor = actor; this.authority = authority; this.channels = channels; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getPhone1() { return phone1; } public void setPhone1(String phone1) { this.phone1 = phone1; } public String getPhone2() { return phone2; } public void setPhone2(String phone2) { this.phone2 = phone2; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public int getActor() { return actor; } public void setActor(int actor) { this.actor = actor; } public String getAuthority() { return authority; } public void setAuthority(String authority) { this.authority = authority; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public Set<Channel> getChannels() { return channels; } public void setChannels(Set<Channel> channels) { this.channels = channels; } }
这里有一个实例,可以参考一下,原文网址:http://duhanlove.blog.sohu.com/68361094.html
最近整理了一下以前做的hibernate的例子.想和大家进行交流.
在hibernate中,one-to-many的例子最典型的是"学生和书"之间的关系,一个学生可以有很多本书,但是每一本书只能属于一个学生,这个简单的例子在hibernate中就称做为一对多的映射关系.
开发hibernate最好的工具我认为要算eclipse了,结合myeclipse插件,可以很好的开发的hibernate.(如果你要开发jsp,可以装lomboz插件,它很好的支持jsp开发,当然不装这个插件也是可以在eclipse下开发jsp的.还有一个emf插件支持j2ee开发,也特别的好!)
首先建立一张表,sql 语句如下:
create database bs
create table student
(sid varchar(32) not null primary key,
sname varchar(16),
sage varchar(16),
)
create table book
(bid varchar(32) not null primary key,
bname varchar(16),
bprice varchar(16),
sid varchar(32)
)
现在表建好了,在eclipse中进行hibernate映射,生成配置文件(本例中是Book.hbm.xml 和Student.hbm.xml文件),
配置文件如下:
//Book.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
<!-- DO NOT EDIT: This is a generated file that is synchronized -->
<!-- by MyEclipse Hibernate tool integration. -->
<!-- Created Thu Apr 21 20:15:18 CST 2005 -->
<hibernate-mapping package="eg">
<class name="Book" table="book">
<id name="bid" column="bid" type="java.lang.String">
<generator class="uuid.hex"/>
</id>
<property name="bname" column="bname" type="java.lang.String" not-null="true" />
<property name="bprice" column="bprice" type="java.lang.String" not-null="true" />
</class>
</hibernate-mapping>
//Student.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
<!-- DO NOT EDIT: This is a generated file that is synchronized -->
<!-- by MyEclipse Hibernate tool integration. -->
<!-- Created Mon Mar 28 16:54:12 CST 2005 -->
<hibernate-mapping package="eg">
<class name="Student" table="student">
<id name="sid" column="sid" type="java.lang.String" unsaved-value="null">
<generator class="uuid.hex"/>
</id>
<property name="sname" column="sname" type="java.lang.String" />
<property name="sage" column="sage" type="java.lang.String" />
<set name="Book" outer-join="false" cascade="all">
<key column="sid"/>
<one-to-many class="Book"/>
</set>
</class>
</hibernate-mapping>
然后写两个Bean类,代码如下:
//Student.java
/*
* Created on 2005-3-28
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package eg;
import java.util.Set;
/**
* @author Administrator
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class Student {
private String sid;
private String sname;
private String sage;
private Set book;
public Student()
{
//must be imply;
}
public String getSid()
{
return sid;
}
public void setSid(String sid)
{
this.sid=sid;
}
public String getSname()
{
return sname;
}
public void setSname(String sname)
{
this.sname=sname;
}
public String getSage()
{
return this.sage;
}
public void setSage(String sage)
{
this.sage=sage;
}
public Set getBook()
{
return this.book;
}
public void setBook(Set book)
{
this.book=book;
}
}
//Book.java
/*
* Created Mon Mar 28 16:55:19 CST 2005 by MyEclipse Hibernate Tool.
*/
package eg;
//import java.io.Serializable;
/**
* A class that represents a row in the 'book' table.
* This class may be customized as it is never re-generated
* after being created.
*/
public class Book
//extends AbstractBook
//implements Serializable
{
private String bid;
private String bname;
private String bprice;
/**
* Simple constructor of Book instances.
*/
public Book()
{
}
/**
* Constructor of Book instances given a simple primary key.
* @param bid
*/
// public Book(java.lang.String bid)
// {
// super(bid);
// }
/* Add customized code below */
public void setBid(String bid)
{
this.bid=bid;
}
public String getBid()
{
return this.bid;
}
public void setBname(String bname)
{
this.bname=bname;
}
public String getBname()
{
return this.bname;
}
public void setBprice(String bprice)
{
this.bprice=bprice;
}
public String getBprice()
{
return this.bprice;
}
}
现在可以写一个测试类来测试hibernate中一对多的Demo了,
/*
* Created on 2005-3-28
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package eg;
//import java.sql.SQLException;
import java.util.*;
//import net.sf.hibernate.cfg.Configuration;
import net.sf.hibernate.*;
/**
* @author Administrator
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class TestOnetoMany {
private SessionFactory sf;
private Session session;
public TestOnetoMany()
{
}
public void doInsert()
{
try
{
session =HibernateSessionFactory.currentSession();
Student student=new Student();
student.setSname("小李");
student.setSage("22");
Set bookset =new HashSet();
Book book=null;
for(int i=0;i<2;i++)
{
book =new Book();
book.setBname("JAVA"+Integer.toString(i));
book.setBprice("50");
bookset.add(book);
//System.out.print("测试........添加数据成功!");
}
student.setBook(bookset);
session.save(student);
session.flush();
session.connection().commit();
}
catch (Exception ex){
ex.printStackTrace();
}
finally
{
try
{
session.close();
}
catch(HibernateException hex2)
{
hex2.printStackTrace();
}
}
System.out.print("插入操作已经结束!............................");
}
//插入操作已经结束.........................................
//开始查询操作.............................................
public void doQuery()
{
try
{
session=HibernateSessionFactory.currentSession();
Query query=session.createQuery("from Student as s ");
List list=query.list();
Student s=null;
//Book book=null;
for(int j=0;j<list.size();j++)
{
s=(Student)list.get(j);
System.out.println("姓名:"+s.getSname());
System.out.println("年龄:"+s.getSage());
System.out.println("所有的书:");
//测试从student中取出的数据
Iterator iterator = s.getBook().iterator();
while(iterator.hasNext())
{
Book book=(Book)iterator.next();
System.out.println("书名:"+book.getBname());
System.out.println("书的价格:"+book.getBprice());
}
// System.out.println("it's ok!");
}
}
catch(HibernateException hex)
{
hex.printStackTrace();
}
catch(Exception ex)
{
ex.printStackTrace();
}
/*catch(SQLException ex)
{
ex.printStackTrace();
}*/
finally
{
try
{
session.close();
}
catch(HibernateException hex3)
{
hex3.printStackTrace();
}
}
}
public static void main(String [] a) throws HibernateException
{
TestOnetoMany test=new TestOnetoMany();
test.doInsert();
test.doQuery();
}
}
注意:session是由sessionFactory创建的,sessionFactory 是线程安全的,但是session不是线程安全的,所以在结束的时候要关闭session.
结束语:
利用myeclipse可以很好的开发hibernate,可以通过数据库表进行hibernate映射,自动生成配置文件(*.hbm.xml)和Bean文件,只需要做适当的修改就可以了.此外,还要在工程中加入hibernate的属性文件(log4j.properties和hibernate.properties),这两个属性文件都是对hibernate工程进行必要的初始化工作,如配置连接数据库方言(dialect)等等,必须和hibernate.cfg.xml配置文件在同一目录下,要不然会出现如下警告信息:
log4j:WARN No appenders could be found for logger (net.sf.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
1.一对多关联关系,使用集合来表示; 2.映射文件中使用<set>标签配置: <set name="集合名"> <key column="数据库中字段名" /> <one-to-many class="集合子元素类名"/> </set> 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"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="connection.username">scott</property> <property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:MGC</property> <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property> <property name="myeclipse.connection.profile">MGC</property> <property name="connection.password">tiger</property> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="show_sql">true</property> <mapping resource="cn/edu/ahau/mgc/hibernate/pojo/Student.hbm.xml" /> <mapping resource="cn/edu/ahau/mgc/hibernate/pojo/Classes.hbm.xml" /> </session-factory> </hibernate-configuration> Student.java: package cn.edu.ahau.mgc.hibernate.pojo; public class Student { private long id; private String name; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } Classes.java: package cn.edu.ahau.mgc.hibernate.pojo; import java.util.Set; public class Classes { private long id; private String name; private Set<Student> students; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Student> getStudents() { return students; } public void setStudents(Set<Student> students) { this.students = students; } } Student.hbm.xml: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping> <class name="cn.edu.ahau.mgc.hibernate.pojo.Student" table="ONE2MANY_STUDENT" schema="SCOTT"> <id name="id" type="java.lang.Long"> <column name="ID" precision="22" scale="0" /> <generator class="native" /> </id> <property name="name" type="java.lang.String"> <column name="NAME" length="20" not-null="true" /> </property> </class> </hibernate-mapping> Classes.hbm.xml: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping> <class name="cn.edu.ahau.mgc.hibernate.pojo.Classes" table="ONE2MANY_CLASSES" schema="SCOTT"> <id name="id" type="java.lang.Long"> <column name="ID" precision="22" scale="0" /> <generator class="native" /> </id> <property name="name" type="java.lang.String"> <column name="NAME" length="20" not-null="true" /> </property> <set name="students"> <key column="CLASSID" /> <one-to-many class="cn.edu.ahau.mgc.hibernate.pojo.Student"/> </set> </class> </hibernate-mapping> HibernateSessionFactory.java: package cn.edu.ahau.mgc.hibernate.many2one.factory; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.Configuration; /** * Configures and provides access to Hibernate sessions, tied to the * current thread of execution. Follows the Thread Local Session * pattern, see {@link http://hibernate.org/42.html }. */ public class HibernateSessionFactory { /** * Location of hibernate.cfg.xml file. * Location should be on the classpath as Hibernate uses * #resourceAsStream style lookup for its configuration file. * The default classpath location of the hibernate config file is * in the default package. Use #setConfigFile() to update * the location of the configuration file for the current session. */ private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); private static Configuration configuration = new Configuration(); private static org.hibernate.SessionFactory sessionFactory; private static String configFile = CONFIG_FILE_LOCATION; static { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } private HibernateSessionFactory() { } /** * Returns the ThreadLocal Session instance. Lazy initialize * the <code>SessionFactory</code> if needed. * * @return Session * @throws HibernateException */ public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession() : null; threadLocal.set(session); } return session; } /** * Rebuild hibernate session factory * */ public static void rebuildSessionFactory() { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } /** * Close the single hibernate session instance. * * @throws HibernateException */ public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } } /** * return session factory * */ public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory; } /** * return session factory * * session factory will be rebuilded in the next call */ public static void setConfigFile(String configFile) { HibernateSessionFactory.configFile = configFile; sessionFactory = null; } /** * return hibernate configuration * */ public static Configuration getConfiguration() { return configuration; } } ExportToDBCreate.java: package cn.edu.ahau.mgc.hibernate.export; import org.hibernate.cfg.Configuration; import org.hibernate.tool.hbm2ddl.SchemaExport; public class ExportToDBCreate { public static void main(String[] args) { Configuration cfg = new Configuration().configure(); SchemaExport export = new SchemaExport(cfg); export.create(true, true); } } ExportDBAdd.java: package cn.edu.ahau.mgc.hibernate.export; import java.util.HashSet; import java.util.Set; import org.hibernate.Session; import cn.edu.ahau.mgc.hibernate.factory.HibernateSessionFactory; import cn.edu.ahau.mgc.hibernate.pojo.Classes; import cn.edu.ahau.mgc.hibernate.pojo.Student; public class ExportDBAdd { public static void main(String[] args) { Session session = HibernateSessionFactory.getSession(); session.beginTransaction(); Set<Student> students = new HashSet<Student>(); for (int i = 0; i < 10; i++) { Student student = new Student(); student.setName("Magci_" + i); session.save(student); students.add(student); } Classes classes = new Classes(); classes.setName("J2EE"); classes.setStudents(students); session.save(classes); session.getTransaction().commit(); HibernateSessionFactory.closeSession(); } }