基于JFinal的数据库配置

发布时间 2023-12-30 10:10:53作者: 椰子灰

参考——

https://blog.csdn.net/weixin_42579328/article/details/89490760

 

1、创建数据表:

CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`pwd` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

2、数据库配置:
①、在resources目录下创建“config.properties”文件:

----------创建.properties的文件的方法前边提到过


//jdbc路径
jdbcUrl=jdbc:mysql://localhost:3306/vrapp?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC

user=root
password=password
//开发模式常量配置
devMode=true
showSql=true
maxActive=100
minIdle=5
initialSize=5

②、config目录下配置:
A、在VrAppConfig的configConstant中配置常量:

public void configConstant(Constants constants) {
//在调用getPropertyToBoolean之前需要先调用loadPropertyFile
loadPropertyFile("config.properties");
//设置jfinal的开发模式
constants.setDevMode(getPropertyToBoolean("devMode",true));
}

B、在VrAppConfig的configPlugin中配置获取连接池:

public void configPlugin(Plugins plugins) {
int initialSize = getPropertyToInt("initialSize");
int minIdle = getPropertyToInt("minIdle");
int maxActive = getPropertyToInt("maxActive");
//获取jdbc连接池
DruidPlugin druidPlugin = new DruidPlugin(getProperty("jdbcUrl"), getProperty("user"), getProperty("password").trim());
druidPlugin.set(initialSize, minIdle, maxActive);
plugins.add(druidPlugin);
//配置ActiveRecordPlugin插件
ActiveRecordPlugin arp = new ActiveRecordPlugin(druidPlugin);
//控制台显示sql语句
arp.setShowSql(getPropertyToBoolean("showSql",true));
plugins.add(arp);
//controller对应的数据表 "user"对应的是数据库中表名,
// User.class对应的是model中的User模型
arp.addMapping("user", User.class);

}


C、model中配置User

package com.model;

import com.jfinal.plugin.activerecord.Model;

import java.util.List;

public class User extends Model<User> {
private static final long serialVersionUID = 1L;
public static final User dao = new User().dao();

/*
//查找用户,用于登录
public List<User> queryUserlist(String name, String pwd){
return find("select * from user where name='"+name+"'and pwd='"+pwd+"'");
}

//添加普通用户
public int addUser(String name, String pwd){
User user = new User();
user.set("name",name);
user.set("pwd", pwd);
user.save();
return 1;
}
*/

}

3、在pom.xml中配置MySQL:

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.29</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>

配置完成