JPA教程 - JPA表名示例

由 haiguiking 创建,youj 最后一次修改 2017-01-09

JPA教程 - JPA表名示例


默认情况下,JPA使用类的简单名称来命名相应的表。

@Entity
@Table(name="EMP")
public class Person {

例子

下面的代码来自Person.java。

package cn.w3cschool.common;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="EMP")
public class Person {
  @Id
  @Column(name = "EMP_ID")
  private long id;
  
  @Basic
  private String name;
  private String surname;
  
  public Person() {}

  public Person(String name, String surname) {
    this.name = name;
    this.surname = surname;
  }
  
  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;
  }
  public String getSurname() {
    return surname;
  }
  public void setSurname(String surname) {
    this.surname = surname;
  }
  @Override
  public String toString() {
    return "Person [id=" + id + ", name=" + name + ", surname=" + surname + "]";
  }
}

下面的代码来自PersonDaoImpl.java。

package cn.w3cschool.common;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

@Transactional
public class PersonDaoImpl {

  @PersistenceContext
  private EntityManager em;
  
  
  public Long save(Person person) {
    em.persist(person);
    return person.getId();
  }
  
  public List<Person>getAll() {
    return em.createQuery("SELECT p FROM Person p", Person.class).getResultList();
  }
  
}

Download Table_Column_Annotation.zip

上面的代码生成以下结果。

以下是数据库转储。

Table Name: EMP
 Row:
    Column Name: EMP_ID,
    Column Type: BIGINT:
    Column Value: 1

    Column Name: NAME,
    Column Type: VARCHAR:
    Column Value: Tom

    Column Name: SURNAME,
    Column Type: VARCHAR:
    Column Value: Smith

 Row:
    Column Name: EMP_ID,
    Column Type: BIGINT:
    Column Value: 2

    Column Name: NAME,
    Column Type: VARCHAR:
    Column Value: Jack

    Column Name: SURNAME,
    Column Type: VARCHAR:
    Column Value: Kook



以上内容是否对您有帮助:
java工程师idea
二维码
建议反馈
二维码