环境:JDK1.6+NetBeans6.5+MySQL5.1
实体类包含主键字段ID:
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
配置PersistenceUnit的时候,如果选用TopLink作为JPA实现:
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="GuestBook-ejbPU" transaction-type="JTA">
<provider>oracle.toplink.essentials.PersistenceProvider</provider>
<jta-data-source>jdbc/guestbook_datasource</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="toplink.ddl-generation" value="create-tables"/>
</properties>
</persistence-unit>
</persistence>
将会生成User表和一个Sequence表,负责生成ID。此时就可以直接插入数据了。
但是如果使用Hibernare作为JPA的实现:
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="GuestBook-ejbPU" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/guestbook_datasource</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
只会生成一个User表。如果直接插入数据则会报主键的错误。此时需要做两件事:
1.在MySQL中给ID设置一个DefaultValue
2.将ID字段设置为自增autoIncrease
ps:TopLink貌似更好用一些