java - @ManyToOne 关系的 PK 未插入

标签 java hibernate spring-mvc jpa

我有一个应用程序(使用注释的 Spring 4 MVC+Hibernate 4+MySQL+Maven 集成示例),使用基于注释的配置将 Spring 与 Hibernate 集成。 我有这个域对象:

@Entity
@Table(name="t_device")
public class Device {

    enum Type {
        IOS, 
        ANDROID
    }



    public Device() {
        super();
    }

    public Device(String key) {
        super();
        this.key = key;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @NotEmpty
    @Size(min=1, max=50)
    @Column(name = "device_key", unique=true, nullable = false)
    private String key;


    @Column(name = "device_desc")
    private String desc;

    @Enumerated(EnumType.STRING)
    @Column(name = "device_type")
    private Type type;


    @OneToOne(fetch=FetchType.EAGER)
    @JoinColumn(name = "application_id", 
                referencedColumnName = "id")
    private Application application;


    public int getId() {
        return id;
    }

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

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public Application getApplication() {
        return application;
    }

    public void setApplication(Application application) {
        this.application = application;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((desc == null) ? 0 : desc.hashCode());
        result = prime * result + id;
        result = prime * result + ((key == null) ? 0 : key.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Device other = (Device) obj;
        if (desc == null) {
            if (other.desc != null)
                return false;
        } else if (!desc.equals(other.desc))
            return false;
        if (id != other.id)
            return false;
        if (key == null) {
            if (other.key != null)
                return false;
        } else if (!key.equals(other.key))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Device [id=" + id + ", key=" + key + ", desc=" + desc + "]";
    }
}

这是链接到另一个:

@Entity
@Table(name="t_device_event")
public class DeviceEvent {

    public class Coordinates {

        @Column(name = "device_lat")
        private Double lat;

        @Column(name = "device_lng")
        private Double lng;


        public Coordinates(Double lat, Double lng) {
            super();
            this.lat = lat;
            this.lng = lng;
        }

        public Double getLat() {
            return lat;
        }

        public void setLat(Double lat) {
            this.lat = lat;
        }

        public Double getLng() {
            return lng;
        }

        public void setLng(Double lng) {
            this.lng = lng;
        }

    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @ManyToOne
    private Device device;

    private Long received;

    private String message;

    @Transient
    private Coordinates coordinates;


    public Coordinates getCoordinates() {
        return coordinates;
    }

    public void setCoordinates(Coordinates coordinates) {
        this.coordinates = coordinates;
    }

    public int getId() {
        return id;
    }

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

    public Device getDevice() {
        return device;
    }

    public void setDevice(Device device) {
        this.device = device;
    }

    public Long getReceived() {
        return received;
    }

    public void setReceived(Long received) {
        this.received = received;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public DeviceEvent(Device device) {
        super();
        this.device = device;
    }   
}

Controller 中的这段代码:

  Device device = deviceService.findByKey("AS3989E506");

    DeviceEvent deviceEvent = new DeviceEvent(device);
    deviceEvent.setCoordinates(deviceEvent.new Coordinates(Double.MIN_VALUE, Double.MAX_VALUE));
    deviceEvent.setMessage("message");
    deviceEvent.setReceived(new Date().getTime());

    deviceEventService.save(deviceEvent);   

和 hibernate 控制台:

hibernate :

  select
        this_.id as id1_1_1_,
        this_.application_id as applicat5_1_1_,
        this_.device_desc as device_d2_1_1_,
        this_.device_key as device_k3_1_1_,
        this_.device_type as device_t4_1_1_,
        applicatio2_.id as id1_0_0_,
        applicatio2_.application_desc as applicat2_0_0_,
        applicatio2_.application_key as applicat3_0_0_ 
    from
        t_device this_ 
    left outer join
        t_application applicatio2_ 
            on this_.application_id=applicatio2_.id 
    where
        this_.device_key=?
Hibernate: 
    insert 
    into
        t_device_event
        (device_id, message, received) 
    values
        (?, ?, ?)
Hibernate: 
    select
        this_.id as id1_1_1_,
        this_.application_id as applicat5_1_1_,
        this_.device_desc as device_d2_1_1_,
        this_.device_key as device_k3_1_1_,
        this_.device_type as device_t4_1_1_,
        applicatio2_.id as id1_0_0_,
        applicatio2_.application_desc as applicat2_0_0_,
        applicatio2_.application_key as applicat3_0_0_ 
    from
        t_device this_ 
    left outer join
        t_application applicatio2_ 
            on this_.application_id=applicatio2_.id

这里的服务:

@Service("deviceEventService")
@Transactional
public class DeviceEventServiceImpl implements DeviceEventService {

    @Autowired
    private DeviceEventDao dao;


    public void save(DeviceEvent deviceEvent) {
        dao.save(deviceEvent);      
    }

}

另一个:

@Service("deviceService")
@Transactional
public class DeviceServiceImpl implements DeviceService {

    @Autowired
    private DeviceDao dao;

    public Device findById(int id) {
        return dao.findById(id);
    }


    public void save(Device device) {
        dao.save(device);
    }


    public void update(Device device) {
        // TODO Auto-generated method stub

    }


    public void delete(Device device) {
        // TODO Auto-generated method stub
    }


    public List<Device> findAll() {
        return dao.findAll();
    }


    public Device findByKey(String key) {
        return dao.findByKey(key);
    }


    public boolean isDeviceKeyUnique(Integer id, String key) {
        Device device = findByKey(key);
        return ( device == null || ((id != null) && (device.getId() == id)));
    }


    public void deleteByKey(String key) {
        dao.deleteByKey (key);  
    }



}

但是表t_device_event的字段device_id为空!

最佳答案

可能是@JoinColumn注解会帮助你

@ManyToOne
@JoinColumn(name="device_id")
private Device device;

关于java - @ManyToOne 关系的 PK 未插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34274646/

相关文章:

java - 继承: Annotate @Id of Super class to child class having different sequences

java hibernate 即使使用 <property name ="hibernate.hbm2ddl.auto">update</property> 也未创建表

java - 我必须在哪里编码模型? (Spring MVC 模板项目)

java - for 循环中的 JTextField 数组将自身添加到布局中

java - Spring 卡夫卡: different json payload on the same topic

java - JPanel 未显示在另一个 JPanel 内

java - 按 ID 跨表拆分 hibernate 实体

java - 从 Spring 3.1.9 迁移到 Spring 4.2.4 时,@Autowired 不起作用。但适用于 Spring 3 和 Java7

java - Controller 排除不起作用

java - 将 MatOfPoint2f 转换为 MatOfPoint