Java - Nutz
Java - Nutz
更新日期:2020-07-24
1. 概览
Nutz是一个轻量级的综合性框架,包含有数据层持久化、IOC、AOP等常用Java框架所包含的功能。
如果是个人写一些比较小的项目,可以使用这个框架。
可以直接参考Nutz的官方网站,都是中文的。
2. 持久层框架
Nutz是一个非常轻量级的框架,相比较MyBatis而言,学习和使用起来非常简单。MyBatis只是配置使用就要费一番功夫。
2.1 基本配置
添加依赖的Jar包,直接搜nutz,名字为org.nutz的那个就是,只需要这一个Jar就可以了。并不需要任何其它复杂的配置文件。
2.2 HelloWorld例子
连接数据库:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 | public class DataSource {
private static SimpleDataSource instance = new SimpleDataSource();
static {
instance.setJdbcUrl("jdbc:postgresql://localhost:5432/postgres");
instance.setUsername("postgres");
instance.setPassword("password");
}
public static SimpleDataSource getInstance() {
return instance;
}
}
|
创建POJO类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 | @Table("mtn_user_info")
public class User {
@Name
// 用户名
private String name;
@Column
// 密码识别子
private String salt;
@Column
// 密码
private String password;
@Column
// 更新日时
private Date update_date;
@Column
// 更新机能
private String update_function_id;
|
Dao类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 | public class TestDao {
// Dao对象,用于进行各种DB操作
private Dao dao;
public TestDao() {
// 创建新的Dao对象
dao = new NutDao(DataSource.getInstance());
}
// 插入一条用户数据
public int insertUser(User user) {
User insertedUser = dao.insert(user);
return insertedUser == null ? 0 : 1;
}
}
|
使用:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 | public class HelloWorld {
public static void main(String[] args) {
TestDao dao = new TestDao();
User user = new User();
user.setName("Zheng Xiaobin");
user.setSalt("MySalt");
user.setPassword(user.getName() + user.getSalt());
user.setUpdate_date(new Date());
user.setUpdate_function_id("Test FUNC");
dao.insertUser(user);
}
}
|
2.3 使用POJO类反向生成表
在Pojo类中,使用@ColDefine来定义列的一些属性。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 | @Table("mtn_user_info")
public class User {
@Name
@ColDefine(notNull=true, width=16)
// 用户名
private String name;
@Column
@ColDefine(notNull=true, width=16)
// 密码识别子
private String salt;
@Column
@ColDefine(notNull=true, width=64)
// 密码
private String password;
@Column
@ColDefine(notNull=true)
// 更新日时
private Date update_date;
@Column
@ColDefine(notNull=true, width=16)
// 更新机能
private String update_function_id;
|
然后使用此Pojo类来创建表:
| dao.create(User.class, true);
|
true表示表存在的时候先Drop掉。