zoukankan      html  css  js  c++  java
  • hibernate--联合主键--XML

    xml:composite-id

    要重写equals,hashCode方法, 还要序列化

    1. 新建一个主键类: StudentPK.java, 注意需要序列化.还要重写equals和hashCode: 

    package com.bjsxt.hibernate;
    
    public class StudentPK implements java.io.Serializable{
    	private int id;
    	private String name;
    	public int getId() {
    		return id;
    	}
    	public void setId(int id) {
    		this.id = id;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	@Override
    	public boolean equals(Object o){
    		if(o instanceof StudentPK){
    			StudentPK pk=(StudentPK)o;
    			if(this.id==pk.getId()&&this.name.equals(pk.getName())){
    				return true;
    			}
    		}
    		return false;
    	}
    	@Override
    	public int hashCode(){
    		return this.name.hashCode();
    	}
    }
    

      

       

    2. 删掉Student.java里的id和name的set和get方法, 新建一个主键对象及setter和getter:     

    package com.bjsxt.hibernate;
    
    public class Student {
    	private StudentPK pk;
    	private int age;
    	public StudentPK getPk() {
    		return pk;
    	}
    	public void setPk(StudentPK pk) {
    		this.pk = pk;
    	}
    	
    	public int getAge() {
    		return age;
    	}
    	public void setAge(int age) {
    		this.age = age;
    	}
    }
    

    3. junit的测试方法改成:

    @Test
    	public void testStudentSave() {
    		StudentPK pk=new StudentPK();
    		pk.setId(1);
    		pk.setName("zhangsan");
    		Student s =new Student();
    		s.setPk(pk);		
    		s.setAge(23);
    		
    		Session session =  sf.openSession();
    		session.beginTransaction();
    		session.save(s);
    		session.getTransaction().commit();
    		session.close();	
    	}
    

      

    4. Student.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">
    <hibernate-mapping package="com.bjsxt.hibernate">
        <class name="Student" table="_student">
            <!-- <id name="id">
            	<generator class="native"></generator>
            </id>
            <property name="name"/> -->
            <composite-id name="pk" class="com.bjsxt.hibernate.StudentPK">
            	<key-property name="id"></key-property>
            	<key-property name="name"></key-property>
            </composite-id>
            
            <property name="age"/>
        </class>
    </hibernate-mapping>
    

      

  • 相关阅读:
    写一个函数的程序,判断是否是浮点数
    写一个函数,输入一个数,随机生成N条邮箱
    day4-python基础知识 <元组&&集合>
    day4-python基础知识<文件操作>
    程序--用户登录--<while循环>
    程序--<猜数字小游戏>--for
    使用ajax后提交事件后禁用按钮,事件执行完毕后,重新启用按钮
    ajax在弹出对话框中实现一个UpdateProgress进度条控件源代码
    运算符的结合性
    匿名方法
  • 原文地址:https://www.cnblogs.com/wujixing/p/5413607.html
Copyright © 2011-2022 走看看