Added by on 2013-07-05

We want to make “userId” and “accountId” primary keys in the table “Account”

Compoundkey.java

@Embeddable
public class Compoundkey implements Serializable{

	private int userId;
	private int accountId;

	public Compoundkey(int userId, int accountId){
		this.userId = userId;
		this.accountId = accountId;
	}
}

 

Account.java

public class Account{

	@Id
	private Compoundkey compk;

	private int accountBalance;
}

 

TestAccount class

public class TestAccount{
	public static void main(){
		AnnotationConfiguration conf = new AnnotationConfiguration5-,
		conf.addAnnotatedClass(School.class);
		new SchemaExport(conf).create(true, true);

		SessionFactory factory = conf.buildSessionFactory();
		Session session = factory.getCurrentSession();
		session.beginTransaction();

		Compundkey key1 = new Compundkey(100, 50);
		Account a1 = new Account();
		a1.setCompoundkey(key1);
		a1.setAccountBalance(30);

		Compundkey key2 = new Compundkey(101, 51);
		Account a2 = new Account();
		a2.setCompoundkey(key2);
		a2.setAccountBalance(31);

		session.save(a1);
		session.save(a2);

		session.getTransaction().commit();
	}
}

Category:

Hibernate

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*