D是关系表 A , B, C他们之间的关系 都是靠D来维护的
我用HIBERNATE 可以写出 A B C的实体BEAN和配置文件 但不知道如何来写关系表D,有没有必要去写这张表的实体BEAN和配置文件呢!
请教!
----------------解决方案--------------------------------------------------------
如果不想偶合度过高,不写D表的实体映射也可以的,如果要写的话就写成3个一对多的关系!
----------------解决方案--------------------------------------------------------
但是如果不写D表的实体映射。hibernate如何来维护它们几张表的关系呢
比如我想A表中插入数据 hibernate会自动在关系D表中插入相应的关系数据吗
我的四张表的关系是这样的:
A表与B表是一对一的关系
B表与C表是一对多的关系(C中的多条记录对应B中的一条记录)
在数据库中通过D表体显出他们的关系。
----------------解决方案--------------------------------------------------------
给你一个一对多的例子给你参考参考!
Teachers.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 name="manytomany.Teachers" table="teachers" catalog="test">
<id name="teacherid" type="java.lang.Integer">
<column name="teacherid" />
<generator class="assigned" />
</id>
<property name="teachername" type="java.lang.String">
<column name="teachername" length="45" not-null="true" />
</property>
<set name="students" inverse="true" table="tea_stu">
<key>
<column name="teacherid" not-null="true" />
</key>
<many-to-many class="manytomany.Students" column="studentid"></many-to-many>
</set>
</class>
</hibernate-mapping>
Students.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 name="manytomany.Students" table="students" catalog="test">
<id name="studentid" type="java.lang.Integer">
<column name="studentid" />
<generator class="assigned" />
</id>
<property name="studentname" type="java.lang.String">
<column name="studentname" length="45" not-null="true" />
</property>
<set name="teachers" inverse="false" table="tea_stu" cascade="save-update">
<key>
<column name="studentid" not-null="true" />
</key>
<many-to-many class="manytomany.Teachers" column="teacherid"></many-to-many>
</set>
</class>
</hibernate-mapping>
----------------解决方案--------------------------------------------------------
Teacher实体类代码:
package manytomany;
import java.util.HashSet;
import java.util.Set;
/**
* Teachers generated by MyEclipse - Hibernate Tools
*/
public class Teachers implements java.io.Serializable {
// Fields
private Integer teacherid;
private String teachername;
private Set students = new HashSet(0);
// Constructors
/** default constructor */
public Teachers() {
}
/** minimal constructor */
public Teachers(Integer teacherid, String teachername) {
this.teacherid = teacherid;
this.teachername = teachername;
}
/** full constructor */
public Teachers(Integer teacherid, String teachername, Set students) {
this.teacherid = teacherid;
this.teachername = teachername;
this.students = students;
}
// Property accessors
public Integer getTeacherid() {
return this.teacherid;
}
public void setTeacherid(Integer teacherid) {
this.teacherid = teacherid;
}
public String getTeachername() {
return this.teachername;
}
public void setTeachername(String teachername) {
this.teachername = teachername;
}
public Set getStudents() {
return this.students;
}
public void setStudents(Set students) {
this.students = students;
}
}
student实体类代码:
package manytomany;
import java.util.HashSet;
import java.util.Set;
/**
* Students generated by MyEclipse - Hibernate Tools
*/
public class Students implements java.io.Serializable {
// Fields
private Integer studentid;
private String studentname;
private Set teachers = new HashSet(0);
// Constructors
/** default constructor */
public Students() {
}
/** minimal constructor */
public Students(Integer studentid, String studentname) {
this.studentid = studentid;
this.studentname = studentname;
}
/** full constructor */
public Students(Integer studentid, String studentname, Set teachers) {
this.studentid = studentid;
this.studentname = studentname;
this.teachers = teachers;
}
// Property accessors
public Integer getStudentid() {
return this.studentid;
}
public void setStudentid(Integer studentid) {
this.studentid = studentid;
}
public String getStudentname() {
return this.studentname;
}
public void setStudentname(String studentname) {
this.studentname = studentname;
}
public Set getTeachers() {
return this.teachers;
}
public void setTeachers(Set teachers) {
this.teachers = teachers;
}
}
----------------解决方案--------------------------------------------------------
DAO类代码:
package manytomany;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class DAO {
public void save(Students students)
{
Session session = HibernateSessionFactory.getSession();
Transaction tx = session.beginTransaction();
session.save(students);
tx.commit();
session.close();
}
}
session工厂类代码:
package manytomany;
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 }.
*/
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;
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;
}
}
操作类代码:
package manytomany;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class InfoOperate extends HttpServlet {
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Students student1 = new Students();
student1.setStudentid(1);
student1.setStudentname("张三");
Students student2 = new Students();
student2.setStudentid(2);
student2.setStudentname("李四");
Teachers teacher1 = new Teachers();
teacher1.setTeacherid(1);
teacher1.setTeachername("中岛");
Teachers teacher2 = new Teachers();
teacher2.setTeacherid(2);
teacher2.setTeachername("田中");
student1.getTeachers().add(teacher1);
student1.getTeachers().add(teacher2);
student2.getTeachers().add(teacher1);
student2.getTeachers().add(teacher2);
DAO dao = new DAO();
dao.save(student1);
dao.save(student2);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to
* post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException
* if an error occure
*/
public void init() throws ServletException {
// Put your code here
}
}
----------------解决方案--------------------------------------------------------
你这是多对多吧 朋友
[此贴子已经被作者于2007-7-27 15:12:38编辑过]
----------------解决方案--------------------------------------------------------
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select max(ID) from user
org.hibernate.PropertyAccessException: IllegalArgumentException occurred while calling setter of com.chen.pojo.User.droits
at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:104)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.setPropertyValues(AbstractEntityTuplizer.java:337)
at org.hibernate.tuple.entity.PojoEntityTuplizer.setPropertyValues(PojoEntityTuplizer.java:200)
at org.hibernate.persister.entity.AbstractEntityPersister.setPropertyValues(AbstractEntityPersister.java:3514)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:272)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:180)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:121)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:186)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:175)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:535)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:523)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:519)
at com.chen.dao.hibernate.UserDao.addUser(UserDao.java:33)
at com.chen.dao.hibernate.test.UserTest.testAddUser(UserTest.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at junit.framework.TestCase.runTest(TestCase.java:154)
at junit.framework.TestCase.runBare(TestCase.java:127)
at junit.framework.TestResult$1.protect(TestResult.java:106)
at junit.framework.TestResult.runProtected(TestResult.java:124)
at junit.framework.TestResult.run(TestResult.java:109)
at junit.framework.TestCase.run(TestCase.java:118)
at junit.framework.TestSuite.runTest(TestSuite.java:208)
at junit.framework.TestSuite.run(TestSuite.java:203)
at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:128)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
Caused by: java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:42)
... 34 more
我为什么抛这个异常!
----------------解决方案--------------------------------------------------------