Java Tutorial/JPA/Primary Key

Материал из Java эксперт
Версия от 05:18, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Define Extra Class For Compound Key

File: Employee.java



import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
@Entity
@IdClass(EmployeePK.class)
public class Employee implements java.io.Serializable {
  private String firstName;
  @Id
  private String lastName;
  @Id
  private long ssn;
  public String getFirstName() {
    return firstName;
  }
  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return lastName;
  }
  public void setLastName(String lastName) {
    this.lastName = lastName;
  }
  public long getSsn() {
    return ssn;
  }
  public void setSsn(long ssn) {
    this.ssn = ssn;
  }
}
class EmployeePK implements java.io.Serializable {
  private String lastName;
  private long ssn;
  public EmployeePK() {
  }
  public EmployeePK(String lastName, long ssn) {
    this.lastName = lastName;
    this.ssn = ssn;
  }
  public String getLastName() {
    return this.lastName;
  }
  public void setLastName(String lastName) {
    this.lastName = lastName;
  }
  public long getSsn() {
    return ssn;
  }
  public void setSsn(long ssn) {
    this.ssn = ssn;
  }
  public boolean equals(Object obj) {
    if (obj == this)
      return true;
    if (!(obj instanceof EmployeePK))
      return false;
    EmployeePK pk = (EmployeePK) obj;
    if (!lastName.equals(pk.lastName))
      return false;
    if (ssn != pk.ssn)
      return false;
    return true;
  }
  public int hashCode() {
    return lastName.hashCode() + (int) ssn;
  }
}





Embedded Compound Primary Key

File: Student.java



import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
@Entity
public class Student implements java.io.Serializable {
    @EmbeddedId
    private StudentId id;
    private String name;

    public Student() {}
    public Student(String country, int id) {
        this.id = new StudentId(country, id);
    }
    public int getId() {
        return id.getId();
    }
    public String getCountry() {
        return id.getCountry();
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public String toString() {
        return "Student id: " + getId() + " name: " + getName() + " country: " + getCountry();
    }
}
@Embeddable
class StudentId  implements java.io.Serializable{
    private String country; 
    @Column(name="Student_ID")
    private int id; 
    public StudentId() {}
    public StudentId(String country, int id) {
        this.country = country;
        this.id = id;
    }

    public String getCountry() { return country; }
    public int getId() { return id; }
    public boolean equals(Object o) { 
        return ((o instanceof StudentId) && 
                country.equals(((StudentId)o).getCountry()) &&
                id == ((StudentId) o).getId());
    }
    public int hashCode() { 
        return country.hashCode() + id; 
    }
}





Id Containing Relationship

File: Helper.java



import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class Helper {
  public static void checkData() throws Exception {
    Class.forName("org.hsqldb.jdbcDriver");
    Connection conn = DriverManager.getConnection("jdbc:hsqldb:data/tutorial", "sa", "");
    Statement st = conn.createStatement();
    ResultSet mrs = conn.getMetaData().getTables(null, null, null, new String[] { "TABLE" });
    while (mrs.next()) {
      String tableName = mrs.getString(3);
      System.out.println("\n\n\n\nTable Name: "+ tableName);
      ResultSet rs = st.executeQuery("select * from " + tableName);
      ResultSetMetaData metadata = rs.getMetaData();
      while (rs.next()) {
        System.out.println(" Row:");
        for (int i = 0; i < metadata.getColumnCount(); i++) {
          System.out.println("    Column Name: "+ metadata.getColumnLabel(i + 1)+ ",  ");
          System.out.println("    Column Type: "+ metadata.getColumnTypeName(i + 1)+ ":  ");
          Object value = rs.getObject(i + 1);
          System.out.println("    Column Value: "+value+"\n");
        }
      }
    }
  }
}





ID Entity With Hash Code And Equals

File: Main.java



import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
public class Main {
  static EntityManagerFactory emf = Persistence.createEntityManagerFactory("JPAService");
  static EntityManager em = emf.createEntityManager();
  public static void main(String[] a) throws Exception {
    em.getTransaction().begin();

    

    em.getTransaction().rumit();
    em.close();
    emf.close();
    Helper.checkData();
  }
}





Not Nullable ID

File: Student.java



import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Student {
  @Id
  @Column(name = "ID", nullable = false)
  private int id;
  transient 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;
  }

  public String toString() {
    return "\n\nID:" + id + "\nName:" + name + "\n\n";
  }
}





Set ID By Yourself

File: Gender.java



public enum Gender {
  MALE, FEMALE
}





Set Primary Key Join Column For Entities In Hierarchy

File: Person.java



import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.PrimaryKeyJoinColumn;
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Person implements java.io.Serializable {
  private int id;
  private String firstName;
  private String lastName;
  @Id
  @GeneratedValue
  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String getFirstName() {
    return firstName;
  }
  public void setFirstName(String first) {
    this.firstName = first;
  }
  public String getLastName() {
    return lastName;
  }
  public void setLastName(String last) {
    this.lastName = last;
  }
}
@Entity
@DiscriminatorValue("CUST")
class Customer extends Person {
  private String street;
  private String city;
  private String state;
  private String zip;
  public String getStreet() {
    return street;
  }
  public void setStreet(String street) {
    this.street = street;
  }
  public String getCity() {
    return city;
  }
  public void setCity(String city) {
    this.city = city;
  }
  public String getState() {
    return state;
  }
  public void setState(String state) {
    this.state = state;
  }
  public String getZip() {
    return zip;
  }
  public void setZip(String zip) {
    this.zip = zip;
  }
}
@Entity
@PrimaryKeyJoinColumn(name = "EMP_PK")
class Employee extends Customer {
  private int employeeId;
  public int getEmployeeId() {
    return employeeId;
  }
  public void setEmployeeId(int id) {
    employeeId = id;
  }
}





Use Current Milisecond As ID

File: Student.java



import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Student {
  @Id
  private long id = System.currentTimeMillis();
  @Basic
  private String name;
  @Basic
  private Date dateOfBirth = new Date();
  public Date getDateOfBirth() {
    return dateOfBirth;
  }
  public void setDateOfBirth(Date dateOfBirth) {
    this.dateOfBirth = dateOfBirth;
  }
  public long getId() {
    return id;
  }
  public void setId(long id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  
  
}





Use UUID As Primary Key

File: Student.java



import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.Lob;
@Entity
public class Student {
  @Id
  private String id;
  private String name;

  
  public String getId() {
    return id;
  }
  public void setId(String id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }

  public String toString() {
    return "\n\nID:" + id + "\nName:" + name + "\n\n";
  }
}