01_8_sql主键生成方式
1. 配置映射文件
<insert id="insertStudentBySequence" parameterClass="Student">
<selectKey resultClass="int" keyProperty="sid">
select studentPKSequence.nextVal as sid from dual
</selectKey>
insert into Student(sid, name, major, birth, score) values(#sid#, #name#, #major#, #birth#, #score#)
</insert>
2. 实现类的方法
public void addStudentBySequence(Student student) {
try {
sqlMapClient.insert("insertStudentBySequence", student);
} catch (SQLException e) {
e.printStackTrace();
}
}
3. 测试
public static void main(String[] args) {
Student student = new Student();
student.setName("星星");
student.setMajor("数学");
student.setScore(10);
student.setBirth(Date.valueOf("2018-01-1"));
student.setSid(12);
IStudentDAO dao = new IStudentDAOImpl();
dao.addStudentBySequence(student);
for(Student stu : dao.queryAllStudent()) {
System.out.println(stu);
}
}
[sid:1, name:李明, major:语文, birth:Tue Mar 27 00:00:00 CST 2018, score:100.0]
[sid:2, name:可可, major:英语, birth:Mon Mar 12 00:00:00 CST 2018, score:120.0]
[sid:3, name:子浩, major:数学, birth:Thu Jan 25 00:00:00 CST 2018, score:100.0]
[sid:22, name:星星, major:数学, birth:Mon Jan 01 00:00:00 CST 2018, score:10.0]