一、ioc
相當于spirng中的ioc,spring中提供了xml與注解的方式加載bean,nutz中提供了json和注解的方式加載bean
1. 配置并獲取bean
1.1 在resource目錄下創(chuàng)建ioc目錄,創(chuàng)建dao.js并配置
這里的date相當于spring中的bean的id,type相當于bean的class
var ioc = {
date: {
type: "java.util.Date"
}
}
1.2 獲取通過NutIoc獲取bean
JsonLoader loader = new JsonLoader("ioc/");
NutIoc ioc = new NutIoc(loader);
Date date = ioc.get(Date.class);
System.out.println(date);
ioc.depose();//關閉ioc容器
2.使用工廠方法實例化
使用靜態(tài)工廠方法
calendar: {
type: "java.util.Calendar",
factory: "java.util.Calendar#getInstance"
}
使用實例工廠方法
calendar: {
type: "java.util.Calendar",
factory: "java.util.Calendar#getInstance"
},
date2: {
factory: "$calendar#getTime"
}
3.向構造方法中注入值
args值類型為一個數(shù)組,數(shù)組中可以傳字符串或者bean,如果為bean,寫法為[{refer: 'beanId'}]
agrs: ['arg']
4.屬性中注入值
fields: {
name: 'zhangsan'
}
5.事件監(jiān)聽
初始化、調用、銷毀
events : {
create : ... , // 創(chuàng)建完成后,各種屬性已經設置好
fetch : ... , // 每次從ioc取出
depose : ... // ioc容器銷毀前,一般用于清理各種資源
}
6.是否單例
singleton : false//默認是單例,如果指定為原型,則容器不會調用depose方法
7.使用注解的方式
7.1配置注解加載器
AnnotationIocLoader loader = new AnnotationIocLoader("com.zbrx.nutz");
NutIoc ioc = new NutIoc(loader);
User user = ioc.get(User.class);
System.out.println(user);
7.2配置bean
可以通過@IocBean(name="user")的方式指定bean的id,默認為首字母小寫
package com.zbrx.nutz.bean;
import org.nutz.ioc.loader.annotation.IocBean;
@IocBean
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
7.3注解中配置其他信息
@IocBean(name="user", singleton=true, create="init", depose="distory" ,
args={"a string", "refer:anotherObject", true, 234} ...)
7.4為屬性注入值
@Inject先按照名字找,再按照類型找,也可以手動指定名字
例:@Inject("user")或@Inject("refer:user")
@Inject
private User user;
8.復合加載器
如何參數(shù)是以號開頭,則是加載器類型,后面的參數(shù)為這個加載器的構造函數(shù)參數(shù),直到遇到下一個號開頭的參數(shù)
也可以用簡寫的形式來定義,如*js, *anno
ComboIocLoader loader = new ComboIocLoader(new String[]{
"*org.nutz.ioc.loader.json.JsonLoader", "ioc/",
"*org.nutz.ioc.loader.annotation.AnnotationIocLoader", "com.zbrx.nutz"
});
二、mvc
配置web.xml
<filter>
<filter-name>nutz</filter-name>
<filter-class>org.nutz.mvc.NutFilter</filter-class>
<init-param>
<param-name>modules</param-name>
<param-value>net.wendal.nutzbook.MainModule</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>nutz</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
配置主模塊(相當于spring中配置xml的位置,nutz是用java編碼的方式)
package net.wendal.nutzbook.;
import org.apache.commons.dbcp.BasicDataSource;
import org.nutz.mvc.annotation.*;
import org.nutz.mvc.ioc.provider.ComboIocProvider;
//開啟注解掃描
@Modules(scanPackage = true)
@Ok("json")//方法正常返回格式
@Fail("json")//方法錯誤返回格式
@IocBy(type= ComboIocProvider.class, args = {
"*org.nutz.ioc.loader.json.JsonLoader", "ioc/",
"*org.nutz.ioc.loader.annotation.AnnotationIocLoader", "com.zbrx.nutz"
})//設置ioc容器
public class MainModule {
}
添加入口函數(shù)
只要添加了@At注解方法是非靜態(tài)public的即為入口函數(shù)。
在入口函數(shù)上可以使用的注解有:
@Ok//成功視圖
@Fail//失敗視圖
@At//入口函數(shù)對應的url,相當于spring中的RequestMapping
接收請求參數(shù)
入口參數(shù)使用@Param("name")String name,
如果是對象,可以使用@Param("..")Pet pet
如果請求參數(shù)名與方法參數(shù)名一致,可以省略@Param
接收屬性參數(shù)
入口參數(shù)使用@Attr("user")User user,獲取request、session中的屬性值,相當于request.getAttribute("user");
返回視圖
@Ok(">>:/user/login")//重定向,等同于@Ok("redirect:/user/login")
@Ok("->:/user/index")//轉發(fā),等同于@Ok("forward:/user/index")
@Ok("jsp:/user/index.jsp")同上
@Ok("json")//返回json字符串
@Ok("raw:png")//返回文件
@Ok("re")//根據(jù)返回值來確定
if (...)
return ">>:/user/login.html";
else
return "jsp:jsp.user.home";
如果需要傳值,在方法參數(shù)列表中加入ViewModel即可
由ioc容器管理mvc
在MainModule上指定
@IocBy(args={
"js", "ioc/",
"anno", "..."http://這里需要注解掃描的類路勁
})
三、Dao
創(chuàng)建java實體
@Table("tb_person")//這里對應數(shù)據(jù)庫表名
public class Person{
@Id//表示該字段為一個自增長的Id,注意,是數(shù)據(jù)庫表中自增!!
private int id;
@Name//表示該字段可以用來標識此對象,或者是字符型主鍵,或者是唯一性約束
private String name;
@Column// 表示該對象屬性可以映射到數(shù)據(jù)庫里作為一個字段
private int age;
...//省略get/set方法
}
Dao常用操作
數(shù)據(jù)庫表操作
1.建表
dao.create(Person.class, false);//這里的false表示如果該表存在,不刪除
//掃描@Table注解并自動建表
//第二個參數(shù)為包名,第三個參數(shù)表示,如果存在,是否刪除
Daos.createTablesInPackage(dao, "net.nutz", false);
2.刪除表
dao.drop(Person.class);//連同數(shù)據(jù)一塊刪除
記錄操作
1.插入一條記錄
//插入一條數(shù)據(jù)并返回id值
Person person = new Person();
person.setName("張三");
person.setAge(23);
dao.insert(person);
System.out.println(person.getId());
//插入數(shù)據(jù)不返回id
dao.fastInsert(person);
2.取出一條數(shù)據(jù)
//根據(jù)名稱獲取 (如果你的實體聲明了 @Name 字段, 字符型主鍵,或者帶唯一性索引的字段)
Person p1 = dao.fetch(Person.class, "張三");
System.out.println(p1.getId());
//根據(jù) ID 獲取 (如果你的實體聲明了 @Id 字段, 數(shù)值型主鍵)
Person p2 = dao.fetch(Person.class, 1);
System.out.println(p2.getName());
@Id和@Name可以同時存在于一個Pojo類內,但不允許標注在同一個屬性,畢竟不可以同時是數(shù)值型主鍵又是字符型主鍵
3.更新一條或多條數(shù)據(jù)
Person p = dao.fetch(Person.class, 1);
p.setAge(18);
dao.update(p);
dao.update(list);//更新一個集合
4.刪除數(shù)據(jù)
//刪除一條數(shù)據(jù)
dao.delete(person);//按照對象刪除
dao.delete(Person.class, 1);//按照id刪除
dao.delete(Person.class, "張三");//按照名字刪除
dao.delete(list);//刪除集合
//刪除表中所有數(shù)據(jù)
dao.clear(Person.class);
//按照條件刪除數(shù)據(jù)
dao.clear(Person.class, Cnd.where("age", ">", "18"));
5.查詢數(shù)據(jù)
//查詢全部
dao.query(Person.class, null);
//按照條件查詢
dao.query(Person.class, Cnd.where("age", ">", "18"));
//分頁查詢
Pager page = dao.createPager(2, 10);
dao.query(Person.class, Cnd.where("age", ">", "18"), page);
6.聚合函數(shù)的操作
dao.func(Person.class, "min", "age");
7.字段過濾
/** 只操作某些字段,如下即只插入name字段,其他操作同樣 */
FieldFilter ff = FieldFilter.create(User.class, "^name$");
ff.run(new Atom() {
@Override
public void run() {
//只插入name字段
User u = new User();
u.setPassword("123456");
u.setName("lisi");
dao.insert(u);
}
});
//或者
User u = new User();
u.setPassword("123456");
u.setName("lisi");
dao = Daos.ext(dao, FieldFilter.create(User.class, "^name$"));
dao.insert(u);
8.一對一關系映射
我們習慣在userInfo表中定義userId,這里正好相反
/* user.id=userInfo.userId */
@Table("tb_user")
public class User {
@Id
private int id;
@Column
private String name;
@Column
private String password;
private int userInfoId;
@One(field="userInfoId")
private UserInfo userInfo;
...//省略get set
}
@Table("tb_user_info")
public class UserInfo {
@Id
private int id;
@Column
private String phone;
...//省略getset
}
//插入操作
User u = new User();
u.setName("zhangsan");
u.setPassword("123456");
UserInfo userInfo = new UserInfo();
userInfo.setPhone("18511558240");
u.setUserInfo(userInfo);
dao.insertWith(u, "userInfo");
//獲取操作
User user = dao.fetch(User.class, 1);
user = dao.fetchLinks(user, "userInfo");
System.out.println(user.getUserInfo().getPhone());
//更新操作
dao.updateWith(user, "userInfo");
//刪除操作
dao.deleteWith(user, "userInfo");
//刪除userInfo
dao.deleteLinks(user, "userInfo");//調用dao.delete挨個刪除
dao.clearLinks(user, "userInfo");//一條sql語句刪除
9.一對多關系映射
@Table("tb_student")
public class Student {
@Id
private int id;
@Column
private String name;
@Column
private int age;
@Column
private int teacherId;
}
@Table("tb_thecher")
public class Teacher {
@Id
private int id;
@Column
private String name;
@Column
private int age;
@Many(field = "teacherId")
private List<Student> student;
}
//插入操作
Teacher t = new Teacher();
t.setName("teacher1");
t.setAge(24);
List<Student> list = new ArrayList<>();
for(int i=0; i<10; i++) {
Student s = new Student();
s.setName("stu"+i);
s.setAge(18);
list.add(s);
}
t.setStudent(list);
dao.insertWith(t, "student");
//查詢操作,其他操作同一對一使用方法相同
Teacher t1 = dao.fetch(Teacher.class, 1);
dao.fetchLinks(t1, "student");
System.out.println(t1.getStudent().get(0).getName());
10.多對多關系映射
@Table("tb_student")
public class Student {
@Id
private int id;
@Column
private String name;
@Column
private int age;
@Column
private int teacherId;
}
@Table("tb_course")
public class Course {
@Id
private int id;
@Column
private String name;
@ManyMany(relation = "tb_student_course", from = "courseId", to = "studentId")
private List<Student> students;
}
@Table("tb_student_Course")
public class StudentCourse {
@Id
private int id;
@Column
private int studentId;
}
//插入操作
Course c = new Course();
c.setName("語文");
List<Student> list = new ArrayList<>();
for(int i=0; i<10; i++) {
Student s = new Student();
s.setName("課程"+i);
·s.setAge(18);
·list.add(s);
}
c.setStudents(list);
dao.insertWith(c, "students");
//其他操作同上
11.自定義sql
使用外部文件sql
//加載sql文件
((NutDao)dao).setSqlManager(new FileSqlManager("sql/"));
Sql sql = dao.sqls().create("select.findAll");
//這里需要注意的是,如果返回一個指定entity的list集合,請使用entities()方法。
//或者可以直接寫sql
//Sql sql = Sqls.create("select * from tb_user");
//使用回調函數(shù)并指定返回類型
sql.setCallback(Sqls.callback.entities());
//設置返回類型實體
sql.setEntity(dao.getEntity(User.class));
//執(zhí)行sql
dao.execute(sql);
List<User> list = sql.getList(User.class);
System.out.println(list);
user.sqls
/* select.findAll */
select * from tb_user
如果要加參數(shù),在sql文件中用"$名稱"和"@名稱"的方式來賦值
DELETE FROM $table WHERE name=@name
變量(var)占位符 - 形式為 $名稱,是將值直接替換,
賦值方式:sql.vars().set("table","t_abc");
參數(shù)(param)占位符 - 形式為 @名稱,使用"?"來替換,用來創(chuàng)建 PreparedStatement
賦值方式:sql.params().set("name","Peter");
使用條件占位符
Sql sql = Sqls.create("SELECT name FROM tb_user $condition");
sql.setCondition(Cnd.where("id", ">", 35));
分頁
Sql sql = Sqls.queryEntity("SELECT * FROM t_pet");
sql.setPager(dao.createPager(2,20));
sql.setEntity(dao.getEntity(Pet.class));
dao.execute(sql);
sql.getList(Pet.class);
12.如何開啟事務
final User user1 = dao.fetch(User.class, 1);
final User user2 = dao.fetch(User.class, 2);
user1.setName("zhangsan");
user2.setName("lisi");
//開啟事務
Trans.exec(new Atom(){
public void run() {
dao.update(user1);
dao.update(user2);
}
});
//關閉事務
可以接受多個Atom作為參數(shù)
public static void exec(Atom... atoms);
四、過濾器
內置過濾器,可以加在主模塊、子模塊、入口函數(shù)上
nutz提供了一個內置過濾器CheckSession ,它的構造函數(shù)需要兩個參數(shù)
1.檢查session什么屬性
2.如果不存在,重定向到哪里
@Filters(@By(type=CheckSession.class, args={"user", "/login.jsp"}))
自定義過濾器
實現(xiàn)ActionFilter接口即可
1.ActionFilter : 返回null即為通過,返回view對象,則表示攔截
如果同時實現(xiàn)AbstractProcessor 接口,通過doNext(ac)繼續(xù)執(zhí)行,具有環(huán)繞功能
五、應用啟動或者關閉時額外處理
1.實現(xiàn)接口Setup
2.主模塊類上添加@SetupBy(MainSetup.class)
使用Setup實現(xiàn)自動創(chuàng)建表
public class MainSetup implements Setup {
@Override
public void init(NutConfig config) {
//獲取ioc容器,從容器中獲取dao
Dao dao = config.getIoc().get(Dao.class);
// 拿到Dao,自然就可以自動建表了
Daos.createTableInPackage(dao, "net.wendal.nutzbook.bean", false);
// 表結構變化了? migration一下
Daos.migration(dao, "net.wendal.nutzbook.bean", true, false);
}
@Override
public void destroy(NutConfig nutConfig) {
}
}
六、異步執(zhí)行
@Async
方法上加入該注解表明該方法時異步的。
七、AOP
聲明aop類
@IocBean
public class TestAop implements MethodInterceptor {
@Override
public void filter(InterceptorChain chain) throws Throwable {
System.out.println("執(zhí)行前");
chain.doChain();
System.out.println("執(zhí)行后");
}
}
使用aop
@At("/ping")
@Aop("testAop")
public String ping(String name) {
System.out.println("執(zhí)行ping方法");
return "success";
}
json方式聲明aop
var ioc = {
txNONE: {
type: "org.nutz.aop.interceptor.TransactionInterceptor",
args: [0]
},
txREAD_UNCOMMITTED: {
type: "org.nutz.aop.interceptor.TransactionInterceptor",
args: [1]
},
txREAD_COMMITTED: {
type: "org.nutz.aop.interceptor.TransactionInterceptor",
args: [2]
},
txREPEATABLE_READ: {
type: "org.nutz.aop.interceptor.TransactionInterceptor",
args: [4]
},
txSERIALIZABLE: {
type: "org.nutz.aop.interceptor.TransactionInterceptor",
args: [8]
},
log: {
type: "org.nutz.aop.interceptor.LoggingMethodInterceptor"
},
$aop : {
type : 'org.nutz.ioc.aop.config.impl.ComboAopConfigration',
fields: {
aopConfigrations: [
{
type: "org.nutz.ioc.aop.config.impl.JsonAopConfigration",
fields : {
itemList : [
['com\\.zbrx\\.nutz\\..+','.+','ioc:log'],
['com\\.zbrx\\.nutz\\..+','.+','ioc:txSERIALIZABLE']
]
}
},
{
type: "org.nutz.ioc.aop.config.impl.AnnotationAopConfigration"
}
]
}
}
};