一对一映射 Hibernate

Posted

技术标签:

【中文标题】一对一映射 Hibernate【英文标题】:One to One mapping Hibernate 【发布时间】:2021-08-18 09:46:44 【问题描述】:

我有两个实体(用户、汽车)。有人可以告诉如何设置这个一对一的映射。我的代码不起作用。错误:org.hibernate.AnnotationException: Unknown mappedBy in: hiber.model.Car.user, referenced property unknown: hiber.model.User.car

用户实体包含加入到 mysqlcarIdCar car 字段。此列是与 cars 表中的 id 链接的外键

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

汽车实体包含用户用户字段

@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 和 @Repository 类:

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

在没有映射的情况下一切正常。实体分别写入数据库。

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);
    
    ...

【问题讨论】:

【参考方案1】:

试试这个方法:

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

【讨论】:

以上是关于一对一映射 Hibernate的主要内容,如果未能解决你的问题,请参考以下文章

SSH进阶之路Hibernate映射——一对一单向关联映射

.Hibernate一对一映射与组件映射

hibernate hibernate一对一关系映射详解

Hibernate一对一映射关联

Hibernate一对一关系映射

Hibernate一对一关联映射配置