更新updatign外键上的关联实体 - Hibernate

时间:2018-01-19 06:41:41

标签: java hibernate spring-transactions

我有一个mysql表,它维护驱动程序的数据并使用外键映射维护驱动程序的城市。

public class Drivers {

    private Integer currentCityId;

    private Integer id;

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }



  @Column(name = "current_city_id")
    public Integer getCurrentCityId() {
        return currentCityId;
    }

    public void setCurrentCityId(Integer currentCityId) {
        this.currentCityId = currentCityId;
    }

    @ManyToOne(fetch = FetchType.EAGER, cascade = { CascadeType.PERSIST, CascadeType.MERGE })
    @JoinColumn(name = "current_city_id", insertable = false, updatable = false, nullable = true, unique = false)
    public Cities getCities() {
        return cities;
    }

    public void setCities(Cities cities) {
        this.cities = cities;
    }

}


@Entity
@Table(name = "cities", catalog = "mytable_production", uniqueConstraints = @UniqueConstraint(columnNames = "name"))
public class Cities implements java.io.Serializable {

    private static final long serialVersionUID = 1L;
    private Integer id;
    private String name;
    private String aliasName1;
    private String aliasName2;
    private int stateId;

}

现在,我通过使用

更新表中的foreignKey值来更新驱动程序的城市
@Transactional 
public void updateCityBizLogic(int driverId,int newCityId) {

    //Some biz logic 
    Drivers d = driversDao.updateCity(driverId,newCityId);

    log.info("Updated driverCity to {}",d.getCities.getName());

}

public class DriversDao {
    @Transactional
    public Drivers updateCity(int DriverId, int newCityId) {

        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Drivers.class);
        criteria.add(Restrictions.eq("id", Integer.parseInt(id)));
        criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
        Drivers d = criteria.list().get(0);

        d.setCurrentCityId(newCityId);
        session.update(d);
        return d;

    }
}

但是在日志行中,它正在打印旧城市名称。我希望会话更新任何外键时更新关联的实体(比如更新连接的城市对象,当我更新cityId时)

有人能指出我在这里失踪并实现它吗?

0 个答案:

没有答案