我正在尝试从 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;
}
}
类联系人看起来很相似。
为什么有“addContact”和“removeContact”方法?这是个好主意吗?我一直习惯 CRUD dao 和服务类。
什么是更好的? “addContact”/“removeContact”方法,或者删除它并将此功能放入 dao/service 类?
最佳答案
addContact 和removeContact 方法是添加到/删除的实用方法
private List<Contact> contacts;
它们不是 dao 的替代品。他们只是填充实体。要从实际数据库中保留/删除,您无论如何都需要编写 DAO 方法。
关于java - Eclipse:从 MySQL 生成实体 - 为什么实体中有 DAO 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23339496/