自分で作ったり提供したりするものは、まず自分自身で使ってみろろということです。自分じゃ使わないものなら人はいくらでも無責任にも無思考にもなれる。そういう投げやりな「サービス」やら「プロダクツ」なんて、だれだってイヤだ。自分が作り手と同時に利用者の立場になれば、ちゃんと使えるレベルのものを提供しようとします。

2012年1月2日月曜日

Hibernate EntityManager 二つクラスを一つテーブルにマッピングする

複数クラスを一つのテーブルにマッピングするサンプルです。

School.java
package com.test;

import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class School {
    private int schoolId;
    private String schoolName;

    private SchoolDetail schoolDetail;

    @Embedded
    public SchoolDetail getSchoolDetail() {
        return schoolDetail;
    }

    public void setSchoolDetail(SchoolDetail schoolDetail) {
        this.schoolDetail = schoolDetail;
    }

    @Id
    @GeneratedValue
    public int getSchoolId() {
        return schoolId;
    }

    public void setSchoolId(int schoolId) {
        this.schoolId = schoolId;
    }

    public String getSchoolName() {
        return schoolName;
    }

    public void setSchoolName(String schoolName) {
        this.schoolName = schoolName;
    }
}

SchoolDetail.java
package com.test;

import javax.persistence.Embeddable;

@Embeddable
public class SchoolDetail {
    private String schoolAddress;
    private boolean isPublicSchool;
    private int studentCount;

    public String getSchoolAddress() {
        return schoolAddress;
    }

    public void setSchoolAddress(String schoolAddress) {
        this.schoolAddress = schoolAddress;
    }

    public boolean isPublicSchool() {
        return isPublicSchool;
    }

    public void setPublicSchool(boolean isPublicSchool) {
        this.isPublicSchool = isPublicSchool;
    }

    public int getStudentCount() {
        return studentCount;
    }

    public void setStudentCount(int studentCount) {
        this.studentCount = studentCount;
    }
}

School.sql
create table School 
(
    schoolId int4 not null, 
    publicSchool boolean not null, 
    schoolAddress varchar(255), 
    studentCount int4 not null, 
    schoolName varchar(255), 
    primary key (schoolId)
)
schoolid publicschool schooladdress studentcount schoolname
1 False newyork 10 usa univercity

0 件のコメント:

コメントを投稿

ホームページ