JPA OneToOne加入问题

时间:2013-10-06 22:53:50

标签: java mysql hibernate jpa orm

这是我的SimpleCost实体

@Entity
@Table(name="Simplecost")
public class SimpleCost {
@Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)  
 private Long id;
 private Long userId;
 private Long cost;
 @OneToOne(cascade=CascadeType.ALL,fetch = FetchType.EAGER)
 @JoinColumn(name = "userId")
 private UserBare user;
}

UserBare:

@Entity
@Table(name="user")
public class UserBare{
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)  
 private Long id;
 private Long userId;
 private String fName;
 private String lName;
}

所以我在填充SimpleCost.user属性时遇到了麻烦。我需要使用SimpleCost.userId来检索用户表数据并填充SimpleCost.user对象。这是我的数据库结构。

数据库表: 用户

CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`fName` varchar(100) DEFAULT NULL,
`lName` varchar(100) DEFAULT NULL,
`mName` varchar(100) DEFAULT NULL,
`title` varchar(100) DEFAULT NULL,
`email` varchar(100) DEFAULT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `id_UNIQUE` (`id`)
 ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;
 /*!40101 SET character_set_client = @saved_cs_client */;

simplecost

CREATE TABLE `simplecost` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`userId` bigint(20) DEFAULT NULL,
`liableCost` decimal(10,2) DEFAULT NULL,
`isActive` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`),
KEY `fk_simplecost_user1_idx` (`userId`),
CONSTRAINT `fk_simplecost_user` FOREIGN KEY (`userId`) REFERENCES `user`      (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

1 个答案:

答案 0 :(得分:1)

您不需要在Entity(java类)中定义的'userId'列。 UserBare中的那个显然无用,并且SimpleCost中的那个将被创建/使用,因为您添加到'用户'字段的@JoinColumn(name = "userId")'

从两个实体声明中删除private Long userId;

除此之外,您还需要定义“填充SimpleCost.user属性时遇到问题”。