Monday, May 20, 2013

Hibernate - @Table, @GeneratedValue, @Column, @Temporal, @Transient and @Lob

See more annotations we use in entity bean class.
@Entity
@Table(name = "STUDENT_INFO") // change name only for the table, but not entity
public class Student {

    @Id
    @GeneratedValue // no need to visibly set ID
    @Column(name = "STUDENT_ID")
    private int ID;

    @Column(name = "FIRST_NAME")
    private String firstName;

    @Column(name = "LAST_NAME")
    private String lastName;

    @Temporal(TemporalType.DATE) // persisted as date yyyy-mm-dd
    @Column(name = "JOIN_DATE")
    private Date joinDate;

    @Transient // not persisted in db
    @Column(name = "ADDRESS")
    private String address;

    @Lob
    @Column(name = "DESCRIPTION")
    private String description;
    ...

Test Code
        Student student = new Student();
        student.setFirstName("James");
        student.setLastName("Bond");
        student.setJoinDate(new Date());
        student.setAddress("Adelaide");
        student.setDescription("Long Description");
        ...

Console output
Hibernate: drop table if exists STUDENT_INFO
Hibernate: create table STUDENT_INFO (STUDENT_ID integer not null auto_increment, DESCRIPTION longtext, FIRST_NAME varchar(255), JOIN_DATE date, LAST_NAME varchar(255), primary key (STUDENT_ID))
Hibernate: insert into STUDENT_INFO (DESCRIPTION, FIRST_NAME, JOIN_DATE, LAST_NAME) values (?, ?, ?, ?)

Execution result in DB










No comments:

Post a Comment