我正在尝试从MySQL生成JPA实体。我用Hibenate。我看了http://www.eclipse.org/webtools/dali/docs/3.2/user_guide/reference001.htm。
这是我数据库的一部分:
CREATE TABLE IF NOT EXISTS `countries` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
`code` CHAR(2) NOT NULL COMMENT 'ISO 3166-1 alpha-2',
PRIMARY KEY (`id`),
UNIQUE INDEX `code_UNIQUE` (`code` ASC))
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `contacts` (
`id` INT NOT NULL AUTO_INCREMENT,
`street` VARCHAR(45) NULL,
`city` VARCHAR(45) NOT NULL,
`psc` VARCHAR(45) NULL,
`state` VARCHAR(45) NOT NULL,
`phone` VARCHAR(45) NULL,
`countries_id` INT NOT NULL,
PRIMARY KEY (`id`),
INDEX `fk_contacts_countries1_idx` (`countries_id` ASC),
CONSTRAINT `fk_contacts_countries1`
FOREIGN KEY (`countries_id`)
REFERENCES `countries` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
Eclipse生成这些实体:
@Entity
@Table(name="countries")
@NamedQuery(name="Country.findAll", query="SELECT c FROM Country c")
public class Country implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String code;
private String name;
//bi-directional many-to-one association to Contact
@OneToMany(mappedBy="country")
private List<Contact> contacts;
public Country() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getCode() {
return this.code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public List<Contact> getContacts() {
return this.contacts;
}
public void setContacts(List<Contact> contacts) {
this.contacts = contacts;
}
public Contact addContact(Contact contact) {
getContacts().add(contact);
contact.setCountry(this);
return contact;
}
public Contact removeContact(Contact contact) {
getContacts().remove(contact);
contact.setCountry(null);
return contact;
}
}
班级联系看起来很相似。
为什么有方法&#34; addContact&#34;和&#34;删除联系人&#34;?这是好主意吗?我一直习惯CRUD dao和服务类。
什么更好? &#34;的addContact&#34; /&#34; removeContact&#34;方法,或删除它并将此功能放到dao / service类?
答案 0 :(得分:2)
addContact和removeContact方法是在
中添加/删除的实用方法private List<Contact> contacts;
他们不是替代品。他们只是填充实体。要从实际数据库中持久保存/删除,您无论如何都需要编写DAO方法。