Mybatis and Spring Integration & Reverse Engineering

Mybatis and Spring Integration & reverse engineering
Mybatis and Spring integration
mybatis impoundment Spring's
goal is to be disposed in SqlMapConfig.xml are transplanted into applicationContext.xml file Spring's
make spring management SqlSessionFactory
let spring management mapper objects and dao.
Use spring and mybatis integrated development mapper proxy and original dao interface.
Automatically open transaction, automatically shut down sqlsession.
Let spring management data source (database connection pool)
import relevant jar package
Configuration File
log4j.properties
SqlMapConfig.xml
applicationContext.xml
integration and development of original dao interfaces
configured SqlSessionFactory and data sources applicationContext.xml ( DBCP connection pool)

<context:property-placeholder location="classpath:jdbc.properties" />

<!-- 数据库连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" >
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- 最大连接数 -->
<property name="maxActive" value="20" />
<!-- 最大等待时间 -->
<property name="maxWait" value="8000" />

<!-- 最大空闲数 -->
<property name="maxIdle" value="3" />
</bean>

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载数据源 -->
<Property name = "dataSource" ref = "dataSource" />
<-! Mybatis loaded core configuration file ->
<Property name = "configLocation" value = "the CLASSPATH: SqlMapConfig.xml" />
<- alias! pack scan ->
<Property name = "typeAliasesPackage" value = "com.syj.mybatis.pojo" />
</ the bean>
development Interface Dao

interface UserDao {public
// querying user ID information according to
public User findUserById (int id) throws Exception;

The fuzzy query name //
public List <the User> findUserByName (String username) throws Exception;
}
Dao implementation class

// Normally we go back SqlSessionDaoSupport can be directly inherited from the direct injection sqlSessionFactory in the Spring configuration
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {

@Override
public User findUserById(int id) throws Exception {
SqlSession sqlSession = this.getSqlSession();
User user = sqlSession.selectOne("user.findUserById", id);
return user;
}

@Override
public List<User> findUserByName(String username) throws Exception {
SqlSession sqlSession = this.getSqlSession();
List<User> list = sqlSession.selectList("user.findUserByName", username);
return list;
}
}
在Spring中配置Dao

<!-- 传统Dao配置 -->
<bean id="userDao" class="com.syj.mybatis.dao.impl.UserDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
测试

public class UserDaoTest {
private ApplicationContext applicationContext;

@Before
public void init() {
applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
}

@Test
public void testFindUserById() throws Exception {
UserDao userDao = applicationContext.getBean(UserDao.class);
User user = userDao.findUserById(32);
System.out.println(user);
}

@Test
public void testFindUserByName () throws Exception {
UserDao userDao = (UserDao) to applicationContext.getBean ( "userDao");
List <the User> userDao.findUserByName List = ( "Zhang");
for (the User User: List) {
the System. Out.println (User);
}
}
}
integration method developed mapper proxy
prepared mapper Interface

interface UserMapper {public
// querying user ID information according to
public User findUserById (int id) throws Exception;

// fuzzy query by name
public List <User> findUserByName (String username) throws Exception;

// Insert Subscriber
public void insertUser (the User User) throws Exception;
}
prepared mapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.syj.mybatis.mapper.UserMapper">
<!-- 根据id查询用户信息 -->
<select id="findUserById" parameterType="int" resultType="user">
SELECT * FROM USER WHERE id = #{id};
</select>

<! - Fuzzy queries the user's information according to the name ->
<SELECT ID = "findUserByName" the resultType = "User"
the parameterType = "String">
the SELECT * the WHERE the FROM the USER username like '% $ {value}%';
</ select>

<! - store user information ->
<INSERT the above mentioned id = "insertUser" parameterType = "the User">

<selectKey keyProperty="id" order="AFTER" resultType="int">
SELECT LAST_INSERT_ID()
</selectKey>

The INSERT the INTO the USER (username, Birthday, Sex, address)
the VALUES
(# {username}, # {Birthday}, # {Sex}, # {address})
</ INSERT>
</ mapper>
of the mapper Spring configuration file map .xml file

<-! Mapper proxy Dao development, the first way -MapperFactoryBean ->
<-!
<Bean the above mentioned id = "UserMapper" class = "org.mybatis.spring.mapper.MapperFactoryBean">
<-! MapperInterface the mapper Interface ->
<Property name = "mapperInterface" value = "com.syj.mybatis.mapper.UserMapper" />
<-! MapperFactoryBean inherited from SqlSessionDaoSupport ->
<Property name = "SqlSessionFactory" ref = "SqlSessionFactory" / >
</ bean>
->

<- mapper dynamic development agency Dao, the second way, the package scanner (recommended)!
MapperScannerConfigurer: mapper scanner, following the package mapper interface to automatically create proxy object
is automatically created to Spring container, bean id is the mapper class name (first letter lowercase)
->
<the bean class = "org.mybatis.spring.mapper.MapperScannerConfigurer">
<! - package scan path configuration, if a plurality of packages to be scanned, using an intermediate half-width, separated by number ->
<Property name = "basePackage" value = "com.syj.mybatis.mapper" />
<- Cause is not used and the above sqlSessionFactory!
<context: Property-placeholder LOCATION = "CLASSPATH: the jdbc.properties" />
conflict
->
<Property name = "sqlSessionFactoryBeanName" value = "SqlSessionFactory" />
</ the bean>
test

Reverse engineering
What is reverse engineering
mybatis programmers need to write your own sql statement, mybatis official reverse engineering, can automatically generate code (mapper.java, mapper.xml, pojo ...) mybatis required for the implementation of a single table that allows programmers We will focus more on complex business logic.

The actual development companies, the commonly used reverse engineering methods: a table in the database -> java code.

The emphasis on the word single table, because the operating Mybatis generated Mapper reverse engineering is carried out for a single table, in large projects, there is little associated with complex multi-table queries, so the role is still very large.

Download Reverse Engineering:

https://github.com/mybatis/generator/releases
here Insert Picture Description

Use of reverse engineering of
how to run a reverse engineering
official website: http: //www.mybatis.org/generator/index.html
here Insert Picture Description

We used reverse engineering to generate Java project
here Insert Picture Description

Reverse engineer the code generated
java engineering structure
herein described is inserted pictures

GeneratorSqlmap.java

package com.syj.mybatis;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

public class GeneratorSqlmap {

public void generator() throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
// 指定逆向工程的配置文件位置
File configFile = new File("./config/generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}

public static void main(String[] args) throws Exception {
try {
GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
generatorSqlmap.generator();
} catch (Exception e) {
e.printStackTrace();
}
}
}

generatorConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
<context ID = "testTables" targetRuntime = "MyBatis 3">
<commentGenerator>
<- true if removed automatically generated annotation:! is: to false: NO ->
<Property name = "suppressAllComments" value = "true "/>
</ commentGenerator>
<- database connections:! driver class, connection address, user name, password ->
<JdbcConnection driverClass =" com.mysql.jdbc.Driver "
the connectionURL =" JDBC: MySQL: / / localhost: 3306 / mybatis168 "userId =" root "
password =" root ">
</ JdbcConnection>
! <- <JdbcConnection driverClass =" oracle.jdbc.OracleDriver "
connectionURL =" jdbc: the Oracle: Thin: @ 127.0.0.1 : 1521: YycG "
userId =" YycG "
password="yycg">
</jdbcConnection> -->

<! - default false, the JDBC DECIMAL and NUMERIC type resolution as Integer, when the true JDBC DECIMAL and
NUMERIC type resolution is java.math.BigDecimal ->
<javaTypeResolver>
<Property name = "forceBigDecimals" value = "to false "/>
</ javaTypeResolver>

<- targetProject:! Position to PO type ->
<javaModelGenerator targetPackage = "com.syj.mybatis.po"
targetProject =. "\ The src">
<- enableSubPackages:! Whether to allow schema package as a suffix - >
<Property name = "enableSubPackages" value = "to false" />
<-! spaces before and after the cleaning values are returned from the database ->
<Property name = "trimStrings" value = "to true" />
</ javaModelGenerator>
<- targetProject:! mapper mapping file generated location ->
<sqlMapGenerator targetPackage = "com.syj.mybatis.mapper"
targetProject =. "\ src">
<- enableSubPackages:! whether to allow schema as a suffix package - ->
<Property name = "enableSubPackages" = value "to false" />
</ sqlMapGenerator>
<- targetPackage:! Mapper interface generation position ->
<javaClientGenerator type = "XMLMAPPER"
targetPackage="com.syj.mybatis.mapper"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 指定数据库表 -->
<table tableName="items"></table>
<table tableName="orders"></table>
<table tableName="orderdetail"></table>
<table tableName="user"></table>
<!-- <table schema="" tableName="sys_user"></table>
<table schema="" tableName="sys_role"></table>
<table schema="" tableName="sys_permission "> </ Table> <-! some fields of the table you need to specify the type of java<Schema Table =" "tableName =" sys_role_permission "> </ Table> ->
<Schema Table =" "tableName =" sys_user_role "> </ Table>



<Table Schema = "" tableName = "">
<columnOverride column = "" the javaType = "" />
</ Table> ->
</ context>
</ generatorConfiguration>
configuration files need to modify the contents of:

Database-driven, address, user name, password

POJO class, mapper interfaces, mapper mapping file generated location

Specifies the data table

main method runs after the configuration is complete GeneratorSqlmap.java will generate the code corresponding to the data table, right after generation remember the name of the project to refresh. If you need to generate again, you must remember to delete the original first generation.

The generated code directory structure
herein described is inserted pictures

We can copy the generated code to the project for testing

Reverse engineering method offered
inquiry

The method of action
selectByExample (TbItemDescExample example) ** query information through a specific restriction, example Criteria for generating a query object to set
selectByPrimaryKey (Long itemId) ** Primary query by
selectByExampleWithBLOBs (TbItemDescExample example) query in accordance with certain constraints, the return value column contains the type of text (default queries do not return the information for the column). Criteria for example to generate a query object to set, and the particular method used is the same as method 1, the only difference is that the return value is all columns.
You can not specify the query column, only able to query all columns.

selectByExample (TbItemDescExample Example)
Example Criteria for generating a query object to set
@Test
public void testSelectByExample () {
// Make Table Example Object
UserExample Example UserExample new new = ();
// generate query conditions are used to set criteria
Criteria criteria example.createCriteria = ();
criteria.andIdIn (Arrays.asList (. 1, 16, 26 is));
//. 1, the query specifying information qualified
// List <the User> List = userMapper.selectByExample (Example);
/ / for (the User User: List) {
// System.out.println (User);
//}
// 2, the total number of query
int = countByExample userMapper.countByExample (Example);
System.out.println (countByExample);
}
Criteria subject to the setting condition will reverse engineering method for generating a multi-table specified
herein described insert pictures
selectByPrimaryKey (Long itemId),
the main key query
selectByExampleWithBLOBs (TbItemDescExample example)
in accordance with certain constraints, query large text
save
the same point: POJOs method parameters are passed, the return value is affected by the number of lines of type int.
insert: insert all the information, if the object passed a property is empty, insert a blank, if the database is set default values, default values on the failure
insertSelective: he would insert attribute contains data for the empty property, not be dealt with, so if the database is provided with a default value, will not be covered by a null value.
Here Insert Picture Description

Update
inserted here pictures described
first type: According to a particular restrictions updated
parameters 1: Pojo name record -> objects to update
parameters 2: Pojo name + Example example -> Criteria object to generate a query set

The method of action
updateByExample (User record, UserExample example) to update the text type (database) of all columns except in accordance with certain constraints.
updateByExampleSelective (Userrecord, UserExample example) to update all the set values of the column in accordance with certain constraints.
II: The update ID
parameter: Pojo, name record -> the object to be updated

The method of action
updateByPrimaryKey (User record) in addition to updating the ID text type (database) all columns
updateByPrimaryKeySelective (User record) set by the ID value to update all columns.
Delete
Method 1: Depending on the particular constraints removed, the specific method used and the time of the query is the same.
Method 2: Remove the primary key.

Guess you like

Origin www.cnblogs.com/ly570/p/11069846.html