使用hibernate在sqlite中插入新行

时间:2014-09-28 20:07:25

标签: java hibernate sqlite

决定在hibernate中使用sqlite。 首先,这只是测试项目。

我的实体类

Address.java

@Entity
@Table(name = "ADDRESS")
public class Address {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID", length = 3, nullable = false, unique = true)
    private Long id;
    @Column(name = "NAME", length = 40, nullable = false)
    private String name;
    @OneToMany(mappedBy = "address", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private Set<Flat> flats;

@Entity
@Table(name="FLAT")
public class Flat {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID", length = 6, unique = true)
    private long id = 1L;
    @Column(name = "CRTN_DATE", nullable = false)
    private Date creationDate;
    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name = "ADDRESS_ID", nullable = false)
    private Address address;
    @Column(name = "ROOM_CNT", length = 1)
    private int roomCount;
    @Column(name = "AREA", length = 4)
    private long totalArea;
    @Column(name = "PHONE", length = 1)
    private String phone;
    @Column(name = "PRICE", length = 7)
    private float price;

所以我的问题: 当我尝试插入像这样的新行时

Flat flat = new Flat();
flat.setTotalArea(45);
flat.setCreationDate(new Date());
flat.setAddress(addressDAO.getByID(3));
flat.setRoomCount(2);
flat.setPrice(68000);
flat.setPhone("Y");
flat.setImages(new HashSet<ImageStorage>());
flatDAO.save(flat);

我在控制台中输出了这样的信息:

Hibernate: insert into FLAT (ADDRESS_ID, CRTN_DATE, PHONE, PRICE, ROOM_CNT, AREA) values (?, ?, ?, ?, ?, ?)
ERROR: [SQLITE_CONSTRAINT]  Abort due to constraint violation (NOT NULL constraint failed: FLAT.ID)

据我了解,Hibernate没有在生成的sql查询中添加空字段(ID)。所以也许有人知道如何解决这个问题? 提前谢谢。

更新

dialect I copied from here

DLL

CREATE TABLE ADDRESS
(
    ID INTEGER PRIMARY KEY NOT NULL,
    NAME TEXT NOT NULL
);
CREATE TABLE FLAT
(
    ID INTEGER PRIMARY KEY NOT NULL,
    CRTN_DATE TEXT NOT NULL,
    ADDRESS_ID INTEGER NOT NULL,
    ROOM_CNT INTEGER NOT NULL,
    AREA REAL NOT NULL,
    PHONE TEXT NOT NULL,
    PRICE REAL NOT NULL,
    FOREIGN KEY (ADDRESS_ID) REFERENCES ADDRESS (ID) DEFERRABLE INITIALLY DEFERRED
);

1 个答案:

答案 0 :(得分:0)

如果将ID列定义为INTEGER PRIMARY KEY,则可以省略insert语句中的ID列(在您的情况下,hibernate会执行此操作)。

查看Autoincrement In SQLite

SQL fiddle中选择此项(在顶部选择sqlite数据库)

模式

CREATE TABLE flat(id INTEGER PRIMARY KEY, name TEXT);

SQL

INSERT INTO flat(name) VALUES('flat 1');
INSERT INTO flat(id, name) VALUES(2, 'flat 2');
INSERT INTO flat(name) VALUES('flat 3');
select * from flat;

<强>更新

我从未使用过sqlite,但根据上面的示例,您的代码应该可以使用。您已将您的ID列定义为INTEGER PRIMARY KEY,而hibernate在其插入的内容中未包含id列。

你确定你没有启用&#34; hibernate.hbm2ddl.auto&#34;?如果您使用hibernate生成表,则该错误对我来说是有意义的,因为您的方言不是使用标识列的INTEGER PRIMARY KEY子句:查看hasDataTypeInIdentityColumn()和{{1 }}