简体   繁体   中英

JPA OneToOne join issue

Here is my SimpleCost Entity

@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;
}

So I'm having an trouble populating SimpleCost.user attribute. I need to use SimpleCost.userId to retreive the user table data and fill the SimpleCost.user object. Here is my database structure.

Database Tables: 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 */;

You don't need the 'userId' columns defined in your Entity (java class). The one in UserBare is obviously useless and the one in SimpleCost will be created/used because of the @JoinColumn(name = "userId") you added to the 'user' field'

Remove private Long userId; from both Entity declaration.

Other than that, you will need to define what is "having an trouble populating SimpleCost.user attribute".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM