问题描述
这是我写的一个方法public boolean addEmployee(Employee emp) {boolean flag = false;Session session = HibernateSessionFactory.getSession();Transaction t = null;try {t = session.beginTransaction();session.save(emp);t.commit();return flag = true;} catch (Exception e) {e.printStackTrace();if (t != null) {t.rollback();}return flag;} finally {session.close();}} public static void main(String[] arge){ Employee emp = new Employee(); EmployeeDAOImpl empl = new EmployeeDAOImpl(); emp.setAge("1976-09-08"); emp.setDepId("LG"); emp.setEmpId("LG20050001"); emp.setEmpName("小王"); emp.setPassword("123"); emp.setSchool("中国科学技术大学"); emp.setSchoolage("硕士"); emp.setSex("男"); emp.setSpeciality("核工业"); empl.addEmployee(emp); }这个是Employee.hbm.xml<hibernate-mapping> <class name="com.xfweb.hibernate.Employee" table="EMPLOYEE" schema="XF"> <id name="empId" type="java.lang.String"> <column name="EMP_ID" length="30" /> <generator class="native" /> </id> <property name="empName" type="java.lang.String"> <column name="EMP_NAME" length="20" /> </property> <property name="password" type="java.lang.String"> <column name="PASSWORD" length="20" /> </property> <property name="sex" type="java.lang.String"> <column name="SEX" length="10" /> </property> <property name="age" type="java.lang.String"> <column name="AGE" length="20" /> </property> <property name="speciality" type="java.lang.String"> <column name="SPECIALITY" length="50" /> </property> <property name="schoolage" type="java.lang.String"> <column name="SCHOOLAGE" length="20" /> </property> <property name="school" type="java.lang.String"> <column name="SCHOOL" length="50" /> </property> <property name="depId" type="java.lang.String"> <column name="DEP_ID" length="20" /> </property> </class></hibernate-mapping>测试以后发现EMP_ID里不是我插入的“LG20050001”而是“4”;这个表我并不希望他插入序列。其他的属性都是正确的。我想可能跟我插入的“Hibernate_sequence”有关。但是我不创建这个序列的话,其他表的序列就报错提示序列不存在。这个应该怎么解决啊?
解决方案
<id name="empId" type="java.lang.String"> <column name="EMP_ID" length="30" /> <generator class="native" /> </id> 改成<id name="empId" type="java.lang.String"> <column name="EMP_ID" length="30" /> <generator class="Assigned" /> </id> Assigned才是將主鍵的生成將給程序處理,與HIbernate無關.