当前位置:网站首页>2、 Idea build jfinal project + automatic code generation + database operation test (three ways)
2、 Idea build jfinal project + automatic code generation + database operation test (three ways)
2022-07-22 19:04:00 【Xiaobai said (๑• ๑)】
List of articles
Two 、IDEA build JFinal project + Code auto generation + Database operation ( Three operation modes )
In the previous chapter , It uses Eclipse Medium JBolt Plug in JFinal The project is built quickly , And the plug-in also provides a variety of rich rapid generation tools , Although it is very convenient, at present, it is still a step-by-step self construction project to better understand JFinal Framework construction project architecture and steps , At the same time, you can also understand various configuration information inside . I also changed another development tool IDEA To build the project , However, the steps and usage are the same as Eclipse It's all the same .
Although the use of maven Can do better jar Package version management , But I decided not to create maven project , Use only the original web Project to build a JFinal Project to test (JFinal The project is consistent with Java Web Standard general items , There is no need to treat him differently ). This project does not explain why it is used so , Just configuration + Use . After getting familiar with , Will target JFinal Learn each component in detail .
1、 Project engineering structure
2、IDEA Create Java Web project
Click on Finish after IDEA The project will be automatically created , So far, one is IDEA establish web The project is over .
3、JFinal Project configuration
Import dependency package
mysql rely on :mysql-connector-java-5.1.38.jar
jfinal rely on :jfinal-4.9.jar
druid Database connection pool dependency :druid-1.1.10.jar
2. To configure web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_4_0.xsd" version="3.0">
<filter>
<filter-name>jfinal</filter-name>
<filter-class>com.jfinal.core.JFinalFilter</filter-class>
<init-param>
<param-name>configClass</param-name>
<!-- Reference resources jfinal Configure the package path of the class -->
<param-value>com.dz.AppConfig</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>jfinal</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
To write jfinal Configuration class —— Inherit JFinalConfig
web.xml This configuration class is configured , When web When the project starts , The configuration class will be loaded .
public class AppConfig extends JFinalConfig { @Override public void configConstant(Constants constants) { // To configure JFinal Constant values } @Override public void configRoute(Routes routes) { // This method is used to configure access routes } @Override public void configEngine(Engine engine) { // This method is used to configure Template Engine } @Override public void configPlugin(Plugins plugins) { // This method is used to configure JFinal Of Plugin } @Override public void configInterceptor(Interceptors interceptors) { // Configure global interceptor } @Override public void configHandler(Handlers handlers) { // This method is used to configure JFinal Of Handler } @Override public void onStart() { // Callback after system startup super.onStart(); } @Override public void onStop() { // Callback before system shutdown super.onStop(); } }
After the above configuration is completed, the project can be deployed to tomcat In the middle , However, this is an empty project, and it makes no sense after it is launched .
remarks :
I am here IDEA Use in Jetty The server startup project has not been successful , Always the server starts successfully but does not load the project ,web.xml File not loaded . If you have friends who know how to solve it or who have read similar articles, you can recommend the connection in the comment area .
4、JFinal Project automatic code generator
/** * Jfinal Code generation tool */
public class JFinalGenerator {
/** * Create a database connection pool , Get database connection information * * @return */
public static DataSource getDataSource() {
DruidPlugin druidPlugin = new DruidPlugin("jdbc:mysql://localhost:3306/jfinal_test?characterEncoding=utf8&useSSL=false&zeroDateTimeBehavior=convertToNull", "root", "root");
druidPlugin.start(); // Start the database connection pool
return druidPlugin.getDataSource(); // Get database connection
}
public static void main(String[] args) {
// base model The package name used
String baseModelPackageName = "com.dz.model.base";
// base model File save path
// System.getProperty("user.dir"): Get the current path of the program
String baseModelOutputDir = System.getProperty("user.dir") + "/src/com/dz/model/base";
System.out.println("baseModelOutputDir File path :" + baseModelOutputDir);
// model The package name used (MappingKit Package name used by default )
String modelPackageName = "com.dz.model";
// model File save path (MappingKit And DataDictionary File default save path )
String modelOutputDir = baseModelOutputDir + "/..";
// Create generator , Create a generator based on the database connection information
Generator generator = new Generator(getDataSource(), baseModelPackageName, baseModelOutputDir, modelPackageName, modelOutputDir);
// Configure whether to generate comments
generator.setGenerateRemarks(true);
// Set database dialect
generator.setDialect(new MysqlDialect());
// Set whether to generate chain setter Method
generator.setGenerateChainSetter(false); //or true
// Add a table name that doesn't need to be generated
//generator.addExcludedTable("adv");
// Is the setting Model In the middle of dao object
generator.setGenerateDaoInModel(false);
// Set whether to generate dictionary files
generator.setGenerateDataDictionary(true);
// Table prefix to be removed
generator.setRemovedTableNamePrefixes("j_");
// Generate
generator.generate();
}
}
A new test database is created jfinal_test, There are two tables in it j_user and j_product, The database fields are not displayed , Generate model that will do .
File directory after generation :
_MapingKit.java: Database and model Map file of , You need to call... In the configuration file , Add mapping relationship .
_DataDictionary.txt: It's a data dictionary , You don't have to generate .
base: The two classes are one-to-one mapping with database fields , You can get the database field value , You can also set values .
Product and User: It inherits two basic classes , By creating a product perhaps user Objects can call set/get Method . The official does not recommend writing database operations in these two classes , You can write if you want .
5、 Database operation
Because it will not be jfinal It uses junit test , So I can only write controller Testing through access . If a friend can do tests or read similar articles, you can send a connection in the comment area .
HelloController.java
// distribution , control , call public class HelloController extends Controller { @Inject private UserService userService; // Automatically inject operations into the business layer UserService user = new UserService(); // Without injection, you can directly new object // test public void getById() { User userById = user.getUserById(2); renderJson(userById); } // Get a group of people public void getUsers() { List<User> users = userService.listUsers(); renderJson(users); } // Get a person public void getUser(@Para("userId") Integer userId) { User userById = userService.getUserById(userId); renderJson(userById); } // Paging to get a group of people public void getPageUsers() { Page<User> userPage = userService.listPageUsers(); renderJson(userPage); } // Insert ( to update ) A person public void saveUserByUpdate() { int i = userService.saveUserByDbUpdate(); renderJson(i); } // Insert ( to update ) A person public void saveUserBySave() { boolean b = userService.saveUserByNewUser(); renderJson(b); } // Insert ( to update ) A person public void saveUserByRecord() { boolean b = userService.saveUserbyRecord(); renderJson(b); } }
UserService.java
// Write sql Statement and business code public class UserService { // This object is shared globally , It can only be used for database query , Cannot host object private static final User userDao = new User().dao(); // Get a group of people public List<User> listUsers() { String sql = "select * from j_user"; List<User> users = userDao.find(sql); return users; } // Paging to get a group of people public Page<User> listPageUsers() { // The current number of pages 1, Two per page return userDao.paginate(1, 2, "select *", " from j_user"); } // Get a person public User getUserById(Integer id) { return userDao.findById(id); } // The above contents are all database query operations , notes :dao Cannot carry data . // Database update operation cannot be used dao To achieve , Can pass Db Tool classes to implement . // Data bearing needs to pass new User().set("",""); Implement or Db.update().Db You can also implement query operations . //Db.update(); insert data public int saveUserByDbUpdate() { String sql = "insert into j_user(name,age,sex) values('yuqd',22,' male ')"; // Mode one int update = Db.update(sql); return update; } //new User().set().set()...save(); Realization public boolean saveUserByNewUser() { // Mode two : Don't want to write sql You can choose this way boolean bool = new User().set("name", "yuqd_2").set("age", "23").set("sex", " male 2").save(); return bool; } public boolean saveUserbyRecord() { // Mode three :Db+Record Data update Record record = new Record().set("name", "yuqd_3").set("age", "24").set("sex", " male 3"); boolean j_user = Db.save("j_user", record); return j_user; } }
AppConfig.java Configuration class
About jfinal Configuration class , Be careful Constant configuration 、 Routing configuration 、 The plug-in configuration The main configuration of the plug-in is DruidPlugin Plug ins and ActiveRecordPlugin, complete model Connection with database tables . Pay attention to this line
_MappingKit.mapping(arp);
public class AppConfig extends JFinalConfig { @Override public void configConstant(Constants constants) { constants.setDevMode(true); constants.setInjectDependency(true); // Turn on dependency injection . constants.setViewType(ViewType.JSP); // Set the page type JSP. } @Override public void configRoute(Routes routes) { routes.add("/", IndexController.class); // Default route page routes.add("/hello", HelloController.class, "/hello"); // The official does not recommend using annotations to configure routes } @Override public void configEngine(Engine engine) { } @Override public void configPlugin(Plugins plugins) { String jdbcUrl = "jdbc:mysql://localhost:3306/jfinal_test?characterEncoding=utf8&useSSL=false&zeroDateTimeBehavior=convertToNull"; String userName = "root"; String password = "root"; // To configure druid Database connection pool plug-in DruidPlugin druidPlugin = new DruidPlugin(jdbcUrl, userName, password); plugins.add(druidPlugin); // To configure ActiveRecord plug-in unit //ActiveRecord yes JFinal One of the core components , // adopt ActiveRecord To manipulate the database , Will greatly reduce the amount of code , Greatly improve development efficiency . ActiveRecordPlugin arp = new ActiveRecordPlugin(druidPlugin); // All mappings are in MappingKit It can be done automatically , For the time being, comment out this part , Untie the annotation after automatic generation _MappingKit.mapping(arp); plugins.add(arp); } @Override public void configInterceptor(Interceptors interceptors) { } @Override public void configHandler(Handlers handlers) { } @Override public void onStart() { super.onStart(); } @Override public void onStop() { super.onStop(); } }
6、 Access test
- By direct new UserService() Object to access service operation .
All the following methods are called by injecting objects .
By injecting service object , Get all users
adopt Id Query the current user
Paging query user information
adopt Db.update(); perform Sql UPDATE statement
adopt new User().set().save() Insert database fields
adopt Db+Record perform sql sentence
The above test results show , The operation results of the database are all successful !
summary
A big piece of nonsense , To sum up, there are two parts , Code auto generation + Database operation .
database Query operation Pass a statement :private static final User userDao = new User().dao(); Call database operation method .
Database update operation :
adopt Db.xxx(); perform sql sentence .
adopt Db+Record; Update the database ,Record Equivalent to general model, call set().save() Operating the database .
adopt new User().set().save(); Operating the database , The way of use is similar to the second .
It can also be modified, such as :
however , You must specify a primary key , Otherwise, there will be abnormalities ...
boolean bool2 = new User().set("name", "yuqd_2").set("age", "23").set("sex", " male 2").set("id", 1).update();
If you have friends, there are other ways to operate the database or some JFinal Interesting articles about operating databases , Welcome to the comment area to connect .
Refer to the connection :
http://www.jfinal.com/feedback/296
http://php-note.com/article/detail/aac226839952464485cdc1c66180bc30
边栏推荐
- 【链表技巧汇总】141.环形链表(简单)
- Go language learning: go language journey (III)
- PTA basic questions 7-28 monkeys choose the king (simple method)
- numpy.reshape完成图像切割
- Go language learning: go language journey (4)
- 程序员面试金典面试题 01.05. 一次编辑
- 1. Closeable of qtablewidget, 2.pro/build_ pass、member,3.QString&&
- JVM-JVM概述
- Flink learning notes (VII) processing function
- BigDecimal中除法divide()方法的详细解析,带你走进源码的world
猜你喜欢
1. Closeable of qtablewidget, 2.pro/build_ pass、member,3.QString&&
There is no session in the tensorflow module
NRF24L01 wireless module setting transmit receive mode method
Flink学习笔记(七)处理函数
1. Access JSON in a way similar to the window path
OSI seven layer network model
Flink学习笔记(六)Flink的时间和窗口
1. Package and release procedure of QT (NSIS);
Wechat scans the QR code of the website, but only displays the link address, and cannot jump to the web page
Leetcode 114. expand binary tree into linked list
随机推荐
[QT source code reuse] simulate the pop-up mode of qcompleter
Leetcode 654. maximum binary tree
OSI七层网络模型
PCV、PIL、Pillow安装
1. The solution of line feed qt5- "vs" in constants; 2. Problems and solutions of common compilation of QT and vs of the same code
Randomly query n pieces of data in various databases
1. MySQL null and in; What is 2.127.0.0.2?
【链表技巧汇总】141.环形链表(简单)
PTA exercise 8-8 judging palindrome string
【YOLOv5实战4】基于YOLOv5的交通标志识别系统-模型测试与评估
PTA 6-11 find the median of self-determined type element sequence (25 points)
1. Qtimer:: how to transfer parameters from singleshot, 2. Qmetaobject:: invokemethod how to transfer values with functions
JVM tuning practice - start from scratch | summary of JVM tuning related to the project
Strncpy() copy string (limited by length)
Flink learning notes (IV) Flink runtime architecture
fucking-algorithm
WGet downloads all files in the directory
mysql执行过程以及顺序
Summary of various materials - Network
Go language learning: go language journey - exercise questions and reference answers