blogjava's web log

blogjava's web log
...

hibernate多对多例子-方便以后查看(三)

1.建表

create   table  student
(sid 
varchar ( 32 not   null   primary   key ,
 sname 
varchar ( 16 ),
 sage 
varchar ( 16 ),
)

create   table  course
(cid 
varchar ( 32 not   null   primary   key ,
cname 
varchar ( 16 )
)

create   table  student_course_link
(sid 
varchar ( 32 not   null ,
cid 
varchar ( 32 not   null ,
primary   key (sid,cid)
)
2.写VO
StudentVO
package com.test;
import java.util.Set;
public class Student
{
    
private String sid;
    
private String sname;
    
private String sage;

    
private Set course;
    
public Student()
    
{
    }

   
//写上get set
Course vo
package com.test;

import java.util.Set;

public class Course
{
    
private String cid;
    
private String cname;
    
private Set student;
   
//写上get set

写配置文件
Student.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
    PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"
>

<hibernate-mapping>

    
<class name="com.test.Student" table="student" >

        
<id name="sid" type="string" unsaved-value="null" >
            
<column name="sid" sql-type="char(32)" not-null="true"/>
            
<generator class="uuid.hex"/>
        
</id>

        
<property name="sname">
            
<column name="sname" sql-type="varchar(16)" not-null="true"/>
        
</property>

        
<property name="sage">
            
<column name="sage" sql-type="varchar(16)" not-null="true"/>
        
</property>

        
<set name="course" table="student_course_link" cascade="all" outer-join="false">
            
<key column="sid"/>
            
<many-to-many class="com.test.Course" column="cid"/>
        
</set>
   
    
</class>

</hibernate-mapping>

Course.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
    PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"
>

<hibernate-mapping>

    
<class name="com.test.Course" table="course" >

        
<id name="cid" type="string" unsaved-value="null" >
            
<column name="cid" sql-type="char(32)" not-null="true"/>
            
<generator class="uuid.hex"/>
        
</id>

        
<property name="cname">
            
<column name="cname" sql-type="varchar(16)" not-null="true"/>
        
</property>

        
<set name="student" table="student_course_link" lazy="false" cascade="all">
            
<key column="cid"/>
            
<many-to-many class="com.test.Student" column="sid"/>
        
</set>
   
    
</class>

</hibernate-mapping>

接着把下面的hibernate.properties文件拷到classes目录下。。这里用的是mysql
hibernate.query.substitutions true 1, false 0, yes 'Y', no 'N'
## MySQL
hibernate.dialect net.sf.hibernate.dialect.MySQLDialect
hibernate.connection.driver_class org.gjt.mm.mysql.Driver
hibernate.connection.url jdbc:mysql://localhost:3306/wjcms
hibernate.connection.username root
hibernate.connection.password wujun
hibernate.connection.pool_size 1
hibernate.proxool.pool_alias pool1
hibernate.show_sql true
hibernate.jdbc.batch_size 0
hibernate.max_fetch_depth 1
hibernate.cache.use_query_cache true 
写测试类了..
package com.test;

import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
import net.sf.hibernate.*;
import java.util.Set;
import java.util.HashSet;
import java.sql.*;
import java.util.List;
import java.util.Iterator;

public class TestManyToMany
{
    SessionFactory sf;
    Session session;
    
public TestManyToMany()
    
{
        
try
        
{
            Configuration cfg 
= new Configuration();
            sf 
= cfg.addClass(Student.class).addClass(Course.class).buildSessionFactory();
        }

        
catch(HibernateException ex)
        
{
            ex.printStackTrace();
        }

    }

    
public void doCreate()
    
{
        
try
        
{
            session 
= sf.openSession();

            Student student 
= new Student();
            student.setSname(
"小王");
            student.setSage(
"22");

            Set courseSet 
= new HashSet();
            Course course 
= null;
            
for(int i=0;i<2;i++)
            
{
                course 
= new Course();
                
if(i==0)
                    course.setCname(
"c++");
                
else if(i==1)
                    course.setCname(
"java");
                courseSet.add(course);
            }

            student.setCourse(courseSet);
            
            session.save(student);
            session.flush();
            session.connection().commit();

        }

        
catch(HibernateException ex)
        
{
            ex.printStackTrace();
        }

        
catch(SQLException ex1)
        
{
            ex1.printStackTrace();
        }

        
finally
        
{
                
try{
                    session.close();
                }

                
catch(HibernateException ex2){
                }

        }


    }

    
public void doQuery()
    
{
        
try{
            session 
= sf.openSession();
            Query q 
= session.createQuery("select s from Student as s");
            List l 
= q.list();
            Student s 
= null;
            Course course 
= null;
            
for(int i=0;i<l.size();i++)
            
{
                s 
= (Student)l.get(i);
                System.out.println(
"姓名: "+s.getSname());
                System.out.println(
"年龄: "+s.getSage());
                System.out.println(
"所选的课程:");
                Iterator it 
= s.getCourse().iterator();
                
while(it.hasNext())
                
{
                    course 
= (Course)it.next();
                    System.out.println(
"课程名: "+course.getCname());
                }



            }


        }

        
catch(HibernateException ex){
            ex.printStackTrace();
        }

        
finally{
            
try{
                session.close();
            }

            
catch(HibernateException ex2){
            }

        }

    }

    
public static void main(String[] args)
    
{
        TestManyToMany t 
= new TestManyToMany();
        
//t.doCreate();
        t.doQuery();
    }

}

 

好。。可以了。。

posted on 2006-04-08 11:11 record java and net 阅读(25580) 评论(18)  编辑  收藏 所属分类: java

评论

# re: hibernate多对多例子-方便以后查看(三) 2006-04-08 11:49 lin

不错啊。。

  回复  更多评论   

# re: hibernate多对多例子-方便以后查看(三) 2006-04-08 11:50 lin

我会常来的。。

希望经常更新。。  回复  更多评论   

# re: hibernate多对多例子-方便以后查看(三) 2006-04-08 15:20 吴某人-不断地学习

:)


  回复  更多评论   

# re: hibernate多对多例子-方便以后查看(三) 2006-04-10 20:30 joyschen

如果不用java Applet 用jsp结合java怎么实现曲线图?
谢谢  回复  更多评论   

# re: hibernate多对多例子-方便以后查看(三) 2006-11-20 21:21 yuxb

我按照你的写的去做了,为什么我的错误是这样的呢》
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not insert collection: [many_to_many.Course.student#31]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1058)
at org.hibernate.action.CollectionRecreateAction.execute(CollectionRecreateAction.java:26)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:248)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:232)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:143)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:297)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:985)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:333)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at many_to_many.Test_Many_To_Many.main(Test_Many_To_Many.java:73)
Caused by: java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]对象名 'Stu_cou' 无效。
at com.microsoft.jdbc.base.BaseExceptions.createException(Unknown Source)
at com.microsoft.jdbc.base.BaseExceptions.getException(Unknown Source)
at com.microsoft.jdbc.sqlserver.tds.TDSRequest.processErrorToken(Unknown Source)
at com.microsoft.jdbc.sqlserver.tds.TDSRequest.processReplyToken(Unknown Source)
at com.microsoft.jdbc.sqlserver.tds.TDSRPCRequest.processReplyToken(Unknown Source)
at com.microsoft.jdbc.sqlserver.tds.TDSRequest.processReply(Unknown Source)
at com.microsoft.jdbc.sqlserver.SQLServerImplStatement.getNextResultType(Unknown Source)
at com.microsoft.jdbc.base.BaseStatement.commonTransitionToState(Unknown Source)
at com.microsoft.jdbc.base.BaseStatement.postImplExecute(Unknown Source)
at com.microsoft.jdbc.base.BasePreparedStatement.postImplExecute(Unknown Source)
at com.microsoft.jdbc.base.BaseStatement.commonExecute(Unknown Source)
at com.microsoft.jdbc.base.BaseStatement.executeUpdateInternal(Unknown Source)
at com.microsoft.jdbc.base.BasePreparedStatement.executeUpdate(Unknown Source)
at org.hibernate.jdbc.NonBatchingBatcher.addToBatch(NonBatchingBatcher.java:23)
at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1039)
... 10 more
  回复  更多评论   

# re: hibernate多对多例子-方便以后查看(三) 2006-11-20 21:23 yuxb

我的关联表是Stu_cou,我一直不知道为什么?请指教!谢谢!  回复  更多评论   

# re: hibernate多对多例子-方便以后查看(三) 2006-11-21 08:28 junmy

Caused by: java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]对象名 'Stu_cou' 无效。






你自己好好找找吧。。




  回复  更多评论   

# re: hibernate多对多例子-方便以后查看(三) 2008-03-23 13:52 xx

删除的代码呢?这才是关键  回复  更多评论   

# re: hibernate多对多例子-方便以后查看(三) 2008-05-14 14:03

你的键写的不对就会出这和情况  回复  更多评论   

# re: hibernate多对多例子-方便以后查看(三) 2008-08-06 00:03 stonegreen

@yuxb
你很可能把默认的数据库设错了,
“对象名无效”一般是这个原因  回复  更多评论   

# re: hibernate多对多例子-方便以后查看(三) 2008-10-14 19:11 王模

Caused by: java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]对象名 'Stu_cou' 无效。

在set里加上 schema="dbo" catalog="OA" //OA是数据库名字
就行了   回复  更多评论   

# re: hibernate多对多例子-方便以后查看(三) 2008-11-01 10:45 woyuanxiaodan

@王模
谢谢 你
在set里加上 schema="dbo" catalog="OA" //OA是数据库名字
我解决了上楼的两个异常问题  回复  更多评论   

# re: hibernate多对多例子-方便以后查看(三) 2011-05-11 21:21 及时回头

@王模
真的挺感谢你的 我加上了
在set里加上 schema="dbo" catalog="OA" //OA是数据库名字

解决了
Caused by: java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]对象名 'Stu_cou' 无效。
异常
  回复  更多评论   

# re: hibernate多对多例子-方便以后查看(三) [未登录] 2011-09-15 08:15 abc

真好,分享了~  回复  更多评论   

# re: hibernate多对多例子-方便以后查看(三) 2011-11-03 17:00 程序员之家

不错正在学  回复  更多评论   

# re: hibernate多对多例子-方便以后查看(三) 2012-07-13 17:14 勿恋勿忘

用sturts 怎么搞?  回复  更多评论   

# re: hibernate多对多例子-方便以后查看(三) 2012-07-13 17:16 勿恋勿忘

js+dom+jsp+servlet(struts)+ajax+hibernate;用这些技术搞? 能搞定吗?
用这些技术跟hibernate结合一起用你能写个例子吗?  回复  更多评论   

# re: hibernate多对多例子-方便以后查看(三) 2013-01-10 14:26 xuan ge

@yuxb
就是不用连接池 jdbc也要有的啊,否则怎么连到数据库  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航:
 

导航

常用链接

留言簿(44)

新闻档案

2.动态语言

3.工具箱

9.文档教程

友情链接

搜索

最新评论