JFinal framework operator KingbaseES V8

1. Basic knowledge of
JFinal jfinal is a relatively new ORM framework. Before starting to configure Jfinal to connect to KingbaseES, I will briefly introduce a basic knowledge of JFinal framework.

What is the ORM framework?

The ORM (Object Relational Mapping) framework uses metadata to describe the details of object-to-relational mapping. Metadata generally uses XML format and is stored in a special object-mapping file.

As long as the mapping relationship between persistent classes and tables is provided, the ORM framework can refer to the information in the mapping file at runtime to persist objects in the database. There are currently five main ORM frameworks: Hibernate (Nhibernate), iBATIS, mybatis, EclipseLink, and JFinal.

ORM uses metadata that describes the mapping between objects and databases. When we think of description, we naturally think of xml and attributes. In the current ORM framework, Hibernate typically uses xml files as describing entity objects. Mapping framework, and the famous Linq uses attributes to describe.

Introduction to JFinal Framework

JFinal is an extremely fast WEB + ORM + AOP + Template Engine framework based on the Java language. Its core design goals are rapid development, less code, simple learning, powerful, lightweight, easy to extend, and Restful. While having all the advantages of the Java language, it also has the development efficiency of ruby, python, php and other dynamic languages!

JFinal has the following main features:

MVC architecture, exquisite design, easy to use

Follow the COC principle (Convention over Configuration is better than the configuration principle), support zero configuration, no xml

Original Db + Record mode, flexible and convenient

ActiveRecord support makes database development extremely fast

Automatically load the modified java file, no need to restart the web server during the development process

AOP support, flexible interceptor configuration and powerful functions

Plugin architecture, strong scalability

Multi-view support, support FreeMarker, JSP, Velocity

Powerful Validator backend verification function

Complete functions, with most of the functions of struts2

Small size only 723 KB, and no third-party dependencies

Brief comparison of JFinal ORM and Hibernate

JFinal uses ActiveRecord to implement database operation support, which is six to ten times faster than Hibernate development efficiency.
JFinal ActiveRecord has a lower learning cost than Hibernate and can be developed within an hour.
JFinal has zero configuration and supports five features for the database: no xml, no annotation, no getter, no setter, and no attribute, which greatly reduces the amount of code, and statistics confirm that the amount of code is reduced by 70% to 95%.
JFinal database operation completely adopts native SQL, which is lower in learning cost than HQL adopted by Hibernate, has more powerful functions, higher performance and good stability.

Two, JFinal use

Several core classes related to Jfinal operation database configuration: JFinalConfig, DruidPlugin, ActiveRecordPlugin, ActiveRecord

JFinalConfig overview

A web project based on JFinal needs to create a subclass inherited from the JFinalConfig class, which is used to configure the entire web project.
The JFinalConfig subclass needs to implement six abstract methods, as shown below:

public class DemoConfig extends JFinalConfig {
    
    
    public void configConstant(Constants me) {
    
    }
    public void configRoute(Routes me) {
    
    }
    public void configEngine(Engine me) {
    
    }
    public void configPlugin(Plugins me) {
    
    }   //数据库相关DruidPlugin配置
    public void configInterceptor(Interceptors me) {
    
    }
    public void configHandler(Handlers me) {
    
    }
}

ActiveRecord

ActiveRecord is one of the core components of JFinal. Operating the database through ActiveRecord will greatly reduce the amount of code and greatly improve development efficiency.

The core of the ActiveRecord model is: a Model object uniquely corresponds to a record in a database table, and the correspondence depends on the primary key value of the database table.

Therefore, ActiveRecord mode requires that the database table must have a primary key. When the database table has no primary key, you can only use the Db + Record mode to operate the database.

ActiveRecordPlugin

ActiveRecord exists as a JFinal Plugin, so you need to configure ActiveRecordPlugin in JFinalConfig when using it.

The following is a sample code for Plugin configuration:

public class DemoConfig extends JFinalConfig {
    
    
  public void configPlugin(Plugins me) {
    
    
  DruidPlugin dp = new DruidPlugin("jdbc:kingbase8://localhost/db_name", "userName", "password");
  //druidPlugin通过Url前缀判定数据库类型,Druid官方配置只适配了V7,只识别前缀jdbc:kingbase,遇见前缀jdbc:kingbase8,会认为是Unknow databaseType导致找不到驱动类, 需要手动指定DriverClass
  dp.setDriverClass("com.kingbase8.Driver");
    me.add(dp);
    ActiveRecordPlugin arp = new ActiveRecordPlugin(dp);
    me.add(arp);
    arp.addMapping("user", User.class);
    arp.addMapping("article", "article_id", Article.class);
  }
}

The above code configures two plug-ins: DruidPlugin and ActiveRecordPlugin, the former is the druid data source plug-in, and the latter is the ActiveRecrod support plug-in. ActiveReceord defines addMapping(String tableName, Class<? extends Model> modelClass>) method, which establishes the mapping relationship between database table name and Model.

In addition, in the above code, arp.addMapping("user", User.class), the primary key name of the table is "id" by default. If the primary key name is "user_id", you need to specify it manually, such as: arp.addMapping("user" , "User_id", User.class).

Model

Model is one of the most important components in ActiveRecord, and it serves as the Model part of the MVC pattern. The following is a sample code for Model definition:

public class User extends Model<User> {
    
    
    public static final User dao = new User().dao();
}

By inheriting Model, the User in the above code immediately has many convenient methods of operating the database. The dao static object declared in User is defined for the convenience of query operations, and this object is not necessary. ActiveRecord-based Model does not need to define attributes, no need to define getter and setter methods, no XML configuration, no Annotation configuration, which greatly reduces the amount of code.

The following are some common usages of Model:

// 创建name属性为James,age属性为25的User对象并添加到数据库
new User().set("name", "James").set("age", 25).save();
 
// 删除id值为25的User
User.dao.deleteById(25);
 
// 查询id值为25的User将其name属性改为James并更新到数据库
User.dao.findById(25).set("name", "James").update();
 
// 查询id值为25的user, 且仅仅取name与age两个字段的值
User user = User.dao.findByIdLoadColumns(25, "name, age");
 
// 获取user的name属性
String userName = user.getStr("name");
 
// 获取user的age属性
Integer userAge = user.getInt("age");
 
// 查询所有年龄大于18岁的user
List<User> users = User.dao.find("select * from user where age>18");
 
// 分页查询年龄大于18的user,当前页号为1,每页10个user
Page<User> userPage = User.dao.paginate(1, 10, "select *", "from user where age > ?", 18);

Dialect multi-database support

Currently ActiveRecordPlugin provides implementation classes for MysqlDialect, OracleDialect, PostgresqlDialect, SqlServerDialect, Sqlite3Dialect, AnsiSqlDialect. MysqlDialect and OracleDialect implement support for Mysql and Oracle respectively, and AnsiSqlDialect implements support for ANSI SQL databases. The following is the configuration code of the database Dialect:
Jincang database KingbaseES V8 can use PostgresqlDialect

public class DemoConfig extends JFinalConfig {
    
    
  public void configPlugin(Plugins me) {
    
    
    ActiveRecordPlugin arp = new ActiveRecordPlugin();
    me.add(arp);
    // 配置kingbase方言,经测试KingbaseES可以使用PostgresqlDialect,需要配置大小写不敏感
    arp.setContainerFactory(new CaseInsensitiveContainerFactory(true));
    arp.setDialect(new PostgresqlDialect());  
  }
}

Test engineering

Test environment:
Development tool: MyEclipse 2018
JDK version: 1.8.0_77
Maven version: 3.6.3
Database: KingbaseES V8 (case insensitive)
JFinal version: 4.9
Druid version: 1.1.22

Dependent library configuration pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.qin</groupId>
  <artifactId>JfinalTest</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>pom</packaging>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
    <jdk.version>1.8</jdk.version>
    <junit.version>3.8.1</junit.version>
    <jfinal.version>4.9</jfinal.version>
    <apachelog4j.version>2.11.1</apachelog4j.version>
    <log4j.version>1.2.17</log4j.version>
	<druid.version>1.1.22</druid.version>
	<postgresql.version>42.2.6</postgresql.version>
</properties>
  
  <dependencies>
  	<dependency>
		<groupId>com.kingbase8</groupId>
		<artifactId>kingbase8</artifactId>
		<version>8.2.0</version>
		<scope>system</scope>
		<systemPath>E:/apache-maven-3.6.3/repository/com/kingbase8/kingbase8/kingbase8-8.2.0.jar</systemPath>
	</dependency>
	<dependency>
	    <groupId>com.jfinal</groupId>
	    <artifactId>jfinal</artifactId>
	    <version>${jfinal.version}</version>
	  </dependency>
	  <dependency>
	    <groupId>com.alibaba</groupId>
	    <artifactId>druid</artifactId>
	    <version>${druid.version}</version>
	</dependency>
  </dependencies>
  
  <build>
    <finalName>JFinalTest</finalName>
	    <plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.6.1</version>
				<configuration>
					<source>${jdk.version}</source>
					<target>${jdk.version}</target>
					<encoding>${project.build.sourceEncoding}</encoding>
					<!-- java8 保留参数名编译参数 -->
					<compilerArgument>-parameters</compilerArgument>
					<compilerArguments>
						<verbose />
					</compilerArguments>
				</configuration>
			</plugin>

			<!-- jar 包中的配置文件优先级高于 config 目录下的 "同名文件" 因此,打包时需要排除掉 jar 包中来自 src/main/resources 
				目录的 配置文件,否则部署时 config 目录中的同名配置文件不会生效 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<version>2.6</version>
				<configuration>
					<excludes>
						<exclude>*.txt</exclude>
						<exclude>*.xml</exclude>
						<exclude>*.properties</exclude>
					</excludes>
				</configuration>
			</plugin>
			
			<!-- 使用 mvn clean package 打包 更多配置可参考官司方文档:http://maven.apache.org/plugins/maven-assembly-plugin/single-mojo.html -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-assembly-plugin</artifactId>
				<version>3.1.0</version>
				<executions>
					<execution>
						<id>make-assembly</id>
						<phase>package</phase>
						<goals>
							<goal>single</goal>
						</goals>

						<configuration>
							<!-- 打包生成的文件名 -->
							<finalName>${project.artifactId}</finalName>
							<!-- jar 等压缩文件在被打包进入 zip、tar.gz 时是否压缩,设置为 false 可加快打包速度 -->
							<recompressZippedFiles>false</recompressZippedFiles>
							<!-- 打包生成的文件是否要追加 release.xml 中定义的 id 值 -->
							<appendAssemblyId>true</appendAssemblyId>
							<!-- 指向打包描述文件 package.xml -->
							<descriptors>
								<descriptor>package.xml</descriptor>
							</descriptors>
							<!-- 打包结果输出的基础目录 -->
							<outputDirectory>${project.build.directory}/</outputDirectory>
						</configuration>
					</execution>
				</executions>
			</plugin>
		 
	  </plugins>
  </build>
</project>

Test main program

import java.util.List;

import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.CaseInsensitiveContainerFactory;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.dialect.PostgreSqlDialect;
import com.jfinal.plugin.druid.DruidPlugin;


public class JFinalTest {
    
    

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		DruidPlugin dp = new DruidPlugin("jdbc:kingbase8://192.168.184.132:54321/TEST", "SYSTEM", "******");
		ActiveRecordPlugin arp=new ActiveRecordPlugin(dp);
		arp.addMapping("USER1","user_id", User1.class);
		dp.setDriverClass("com.kingbase8.Driver");
		arp.setContainerFactory(new CaseInsensitiveContainerFactory(true));  //设置应用中字估名大小写不敏感
		arp.setDialect(new PostgreSqlDialect());  //kingbase设置大小写不敏感,可以使用postgresqlDialect
		dp.start();
	    arp.start();
//	    User1 info1=new User1().set("name", "Lilei").set("AGE", 27); //插入数据
//	    info1.save();
//	    User1.dao.deleteById(3); //删除数据
//	    User1.dao.findById("6").set("AGE","30").update();
//	    User1 user = User1.dao.findByIdLoadColumns(6, "name, age");
//	    String userName = user.getStr("name");
//	    Integer userAge = user.getInt("age");
//	    System.out.println("name="+userName+";userAge="+userAge+";");
	    Page<User1> userPage = User1.dao.paginate(1, 3, "select *", "from user1 where age > ?", 18);
	    List<User1> ul=userPage.getList();
	    for(User1 s: ul){
    
    
	    	System.out.println(s.getInt("user_id")+" "+s.getStr("name")+" "+s.getInt("age"));
	    }
	}

}

references:

1、https://jfinal.com/doc
2、https://jfinal.com/project/1
3、https://baike.baidu.com/item/JFinal/9383157?fr=aladdin

Guess you like

Origin blog.csdn.net/sxqinjh/article/details/109142395
v8