简体   繁体   中英

One to One mapping Hibernate

I have two entity (User, Car). Can someone tell how to set this one to one mapping. My code not working. Error: org.hibernate.AnnotationException: Unknown mappedBy in: hiber.model.Car.user, referenced property unknown: hiber.model.User.car

User entity contains Car car field joined to mysql column carId . This column is foreign key linked with id in cars table

@Entity
@Table(name = "users")
public class User {
    ...
    @OneToOne
    @JoinColumn(name = "carId")
    private Car car;
    ...
}

Car entity contains User user field

@Entity
@Table(name = "cars")
public class Car {
    ...
    @OneToOne(mappedBy = "car")
    private User user;
    ...
}

public class Main {
    ...
    UserService userService = context.getBean(UserService.class);
    CarService carService = context.getBean(CarService.class);
      
    User user1 = new User("User1", "Lastname1", "user1@mail.ru");
    Car car1 = new Car("Car", 1);
    
    carService.add(car1);
    user1.setCar(car1);
    userService.add(user1); 
    ...
}

@Service and @Repository classes:

public class UserServiceImpl {
    ...
    @Autowired
    private UserDao userDao;
   
    public void add(User user) {
      userDao.add(user);
    }
    ...
}

Everything worked without mapping. Entities are written to database separately.

public class UserDaoImpl {
    ...
    @Autowired
    private SessionFactory sessionFactory;
    
    public void add(User user) {
      System.out.println(user.toString());
      sessionFactory.getCurrentSession().save(user);
    }
    ...
}

public class CarServiceImpl {
    ...
    @Autowired
    private CarDao carDao;
    
    public void add(Car car) {
        carDao.add(car);
    }
    ...
}

public class CarDaoImpl {
    ...
    @Autowired
    private SessionFactory sessionFactory;
    
    public void add(Car car) {
        sessionFactory.getCurrentSession().save(car);
    }
    ...
}

Try this way:

@Entity
@Table(name = "users")
public class User {
    ...
    @OneToOne
    @JoinColumn(name = "carId")
    private Car car;
    ...
}

@Entity
@Table(name = "cars")
public class Car {
    ...
    @OneToOne(mappedBy = "car")
    @JoinColumn(name = "userId")
    private User user;
    ...
}

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