你没有说你使用的是哪个数据库,所以我假设它是 MySQL。
这些是我们的桌子。请注意user_id和user_flag_id之间的一对一映射以及on delete cascade on update cascade子句。
CREATE TABLE `user` (
`user_id` int(11) NOT NULL DEFAULT '0',
`user_name` varchar(32) DEFAULT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB;
CREATE TABLE `user_flag` (
`user_flag_id` int(11) NOT NULL DEFAULT '0',
`user_flag_name` varchar(32) DEFAULT NULL,
PRIMARY KEY (`user_flag_id`),
CONSTRAINT `fk_user_id` FOREIGN KEY (`user_flag_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB;
鉴于这些,您可以创建如下映射。
@Entity(name = "user")
@Table(schema = "test", name = "user")
public final class User {
@Id
@Column(name = "user_id")
public int id;
@Basic
@Column(name = "user_name")
public String name;
}
@Entity(name = "user_flag")
@Table(schema = "test", name = "user_flag")
public final class UserFlag {
@Id
@Column(name = "user_flag_id")
public int id;
@Basic
@Column(name = "user_flag_name")
public String name;
@OneToOne
@JoinColumn(name = "user_flag_id", referencedColumnName = "user_id")
public User user;
}
假设我们有以下数据。
+---------+-----------+
| user_id | user_name |
+---------+-----------+
| 1 | Joe |
| 2 | Jane |
| 3 | Jacob |
+---------+-----------+
+--------------+----------------+
| user_flag_id | user_flag_name |
+--------------+----------------+
| 1 | Joe's flag |
| 3 | Jacob's flag |
+--------------+----------------+
下面的代码将证明,如果你删除一个用户,它的关联标志将被删除(但不是相反)。
@Test
public void test() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("test");
EntityManager em = emf.createEntityManager();
EntityTransaction et = em.getTransaction();
// prints out our three users, Joe, Jane and Jacob
for (User u : em.createQuery(String.format("select u from %s u", User.class.getName()), User.class)
.getResultList())
System.out.format("User{id=%s, name=%s}\n", u.id, u.name);
// prints out Joe's and Jacob's flags
for (UserFlag uf : em.createQuery(String.format("select uf from %s uf", UserFlag.class.getName()), UserFlag.class)
.getResultList())
System.out.format("UserFlag{id=%s, name=%s}\n", uf.id, uf.name);
et.begin();
User jacob = em.find(User.class, 3);
em.remove(jacob);
et.commit();
// prints out our remaining users, Joe and Jane
for (User u : em.createQuery(String.format("select u from %s u", User.class.getName()), User.class)
.getResultList())
System.out.format("User{id=%s, name=%s}\n", u.id, u.name);
// prints out Joe's flag
for (UserFlag uf : em.createQuery(String.format("select uf from %s uf", UserFlag.class.getName()), UserFlag.class)
.getResultList())
System.out.format("UserFlag{id=%s, name=%s}\n", uf.id, uf.name);
em.close();
emf.close();
}
此示例假设您选择的引擎是 InnoDB。但是,如果您想使用 MyISAM,您可以使用 triggers模拟on update cascade on delete cascade子句。