下面是oracl和nutz配合实现主键自增。
第一步:在数据库里完成主键自增的机制。
1,创建表T_PERSON(设置id字段为主键)
-- Create table create table T_PERSON ( ID NUMBER not null, NAME NVARCHAR2(60), PASSWORD NVARCHAR2(60), ADDRESSID NUMBER ) tablespace SYSTEM pctfree 10 pctused 40 initrans 1 maxtrans 255 storage ( initial 64K minextents 1 maxextents unlimited ); -- Create/Recreate primary, unique and foreign key constraints alter table T_PERSON add constraint PK_PERSON primary key (ID) using index tablespace USERS pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K minextents 1 maxextents unlimited );
2,创建序列(实现主键自增的必要前提)
--创建序列(实现person,address主键自增的必要序列) create sequence seq_nutz increment by 1 start with 1 maxvalue 999999999;
3,给要主键自增的表上创建触发器(在插入前利用触发器给主键id赋值)
--给person表创建触发器--实现主键自增 CREATE TRIGGER trigger_pk_person BEFORE insert ON T_PERSON FOR EACH ROW begin select seq_nutz.nextval into:New.id from dual; end;
4,测试
插入sql:
INSERT INTO t_person(NAME,password,Addressid) VALUES('陈超阳','123456789','24');再次查询该条记录已经有了id 42了。
至此数据库设计已经ok。
第二步:nutz插入:
1,数据库实体模型设计
package com.supan.nuts.module; import org.nutz.dao.entity.annotation.Column; import org.nutz.dao.entity.annotation.Id; import org.nutz.dao.entity.annotation.One; import org.nutz.dao.entity.annotation.Table; @Table("T_PERSON") public class Person { //ID表示使用数据库的自增(默认的) @Id private Integer id; @Column("name") private String name; @Column("password") private String password; @Column("addressId") private Integer addressId; @One(target = Address.class,field = "addressId") private Address address; //省略getter setter.... }
2,插入的action。
package com.supan.nuts.action; import org.nutz.dao.impl.NutDao; import org.nutz.ioc.loader.annotation.Inject; import org.nutz.ioc.loader.annotation.IocBean; import org.nutz.mvc.adaptor.JsonAdaptor; import org.nutz.mvc.annotation.AdaptBy; import org.nutz.mvc.annotation.At; import org.nutz.mvc.annotation.Ok; import org.nutz.mvc.annotation.Param; import com.supan.nuts.module.Person; @IocBean public class PersonAction { @Inject private NutDao dao; @At("/insertPerson") @Ok("json") @AdaptBy(type=JsonAdaptor.class) public String insertPerson(@Param("..") Person person) { dao.insertWith(person, "address"); return "success"; } public NutDao getDao() { return dao; } public void setDao(NutDao dao) { this.dao = dao; } }