Composite Primary Keys In Hibernate | Code Factory






Download code and jars : Link.

File : ProjectId.java

package com.codeFactory.bean;

import java.io.Serializable;

public class ProjectId implements Serializable{

int departmentId;
int projectId;

public int getDepartmentId() {
return departmentId;
}
public void setDepartmentId(int departmentId) {
this.departmentId = departmentId;
}
public int getProjectId() {
return projectId;
}
public void setProjectId(int projectId) {
this.projectId = projectId;
}

}




File : Project.java

package com.codeFactory.bean;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;

@Entity
@IdClass(ProjectId.class)
public class Project {

@Id int departmentId;
@Id int projectId;
public int getDepartmentId() {
return departmentId;
}
public void setDepartmentId(int departmentId) {
this.departmentId = departmentId;
}
public int getProjectId() {
return projectId;
}
public void setProjectId(int projectId) {
this.projectId = projectId;
}
}




File : Action.java

package com.codeFactory.action;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

import com.codeFactory.bean.Project;

public class Action {

static AnnotationConfiguration annotationConfiguration;
static SessionFactory sessionFactory;
public static void main(String args[])
{
annotationConfiguration = new AnnotationConfiguration();
sessionFactory = annotationConfiguration.configure("hibernate.cfg.xml").buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = null;
try
{
transaction = session.beginTransaction();
Project project = new Project();
project.setProjectId(1);
project.setDepartmentId(2);
session.save(project);
transaction.commit();
System.out.println("Saved.");
session.close();
}
catch(Exception e)
{
System.out.println("Exception : " + e);
}
}
}



File : 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">

<hibernate-configuration>

<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<mapping class="com.codeFactory.bean.Project"/>
</session-factory>

</hibernate-configuration>

Comments

Popular posts from this blog

How to get IP address and MAC address of client in java | #CodeFactory

At Least One Checkbox Is Checked From All CheckBox Group | #CodeFactory

FTP Connection In Installed Alfresco | Code Factory