Sandah Aung
Sandah Aung

Reputation: 6188

Hibernate returning null for @OneToOne

I defined this relationship in my User class:

@OneToOne (cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn (name = "id")
    private Balance balance;

Hibernate creates necessary tables with the right relationships.

However, when I retrieve User objects using the following code, Balance is set null.

User fetchedUser = userRepository.findOne(id);        
Balance balance = fetchedUser.getBalance();

Why is this?

(I use Spring Data for data access.)

Edit:

This code generates the users table:

CREATE TABLE `users` (
    `id` BIGINT(20) NOT NULL AUTO_INCREMENT,
    `contact_number` VARCHAR(255) NOT NULL,
    `date_created` DATE NOT NULL,
    `date_of_birth` DATE NOT NULL,
    `device_id` VARCHAR(255) NOT NULL,
    `email` VARCHAR(255) NULL DEFAULT NULL,
    `gender` TINYINT(1) NOT NULL,
    `location` VARCHAR(255) NOT NULL,
    `name` VARCHAR(255) NOT NULL,
    `password` VARCHAR(255) NOT NULL,
    `username` VARCHAR(255) NOT NULL,
    `balance_id` BIGINT(20) NULL DEFAULT NULL,
    PRIMARY KEY (`id`),
    INDEX `FK6A68E08CBE6702` (`balance_id`),
    CONSTRAINT `FK6A68E08CBE6702` FOREIGN KEY (`balance_id`) REFERENCES `balances` (`id`)
)

And this generates balances

CREATE TABLE `balances` (
    `id` BIGINT(20) NOT NULL AUTO_INCREMENT,
    `total_claimed` INT(11) NOT NULL,
    `total_won` INT(11) NOT NULL,
    PRIMARY KEY (`id`)
)

Upvotes: 2

Views: 3267

Answers (2)

bgth
bgth

Reputation: 460

Please add Foreign Key Constraint and then try again.

CREATE TABLE `balances` (
   `balance_id` BIGINT(20) NOT NULL AUTO_INCREMENT,
   `total_claimed` INT(11) NOT NULL,
   `total_won` INT(11) NOT NULL,
   `user_id` BIGINT(20),
   PRIMARY KEY (`id`)
)

alter table balances add constraint XFK_USER foreign key (user_id)
  references users (id);

Upvotes: 0

Blekit
Blekit

Reputation: 663

In @JoinColumn annotation name references the column which stores foreign key to the other part of relationship. I can only assume, that in your mapping column id stores identifier (PrimaryKey) of the User. Maybe it should be something like:

@OneToOne(cascade = CascadeType.ALL)
@JoinColum(name = "balance_id" referencedColumnName = "id")
private Balance balance;

Above mapping will work when following requirements are met:

  • column in USERS table pointing to associated record in BALANCES table is named balance_id
  • PrimaryKey column in BALANCES table is named id

If names used in your application differ, you'll have to adjust this mapping accordingly.

Additionally maybe you want the relationship to be bidirectional. In this case you should add following mapping to Balance entity:

@OneToOne(mappedBy = "balance")
private User user;

Upvotes: 2

Related Questions