mybatis Learning Framework - parameter types, the return type

1. parameterType configuration parameters

SQL statement parameter passing, parameterType property using labels to set.

Value of the attribute may be a primitive type, a reference type (e.g.: String Type),

It may also be a type of entity classes (POJO class). But you can also use a wrapper class entity class 

String basic types and we can directly write the type name, the way you can use the package name of the class name, for example:.
Java.lang.String.
The reason is mybaits when loading has put commonly used data types registered an alias, so we use can not write the package name
if we write class also registered an alias, you can also write an alias directly (through typeAliases label)

TypeAliasRegistery.class can refer to the source.

mybatis ognl using expression analysis target value of the field or the value $ # {} {} is the object attribute name pojo

OGNL expression: 
    Object Graphic Navigation Language 
     object graph navigation language 
 
    it is to get the data value method of the object. In writing to get to omit. 
    For example: We get the user name of the 
        class in writing: user.getUsername (); 
        OGNL written expression: user.username 
    the mybatis Why can write username directly, without user it: 
        because parameterType already provided the property belongs class, so in this case you do not need to write the object name

 

1.1 Basic Types

    <select id="findById" resultType="account">
        select * from account where id = #{id}
    </select>

1.2 Reference types

    <select id="findByName" parameterType="string" resultType="account">
        select * from account where name like #{name}
    </select>

1.3 Entity Type

    <insert id="saveAccount" parameterType="account">
        insert into account(name,money) VALUES (#{name},#{money});
    </insert>

1.4 entity class packaging

Development by pojo pass the query, the query is an integrated query, include not only the user's query conditions also include other search
query conditions that can make up an object, called a query object, then you can use the wrapper object pass input parameter.

AccountVo类
public class AccountVo {
    private Account account;

    public Account getAccount() {
        return account;
    }
    public void setAccount(Account account) {
        this.account = account;
    }
}


AccountMapper接口中的方法
List<Account> findByVo(AccountVo accountVo);

mapper.xml中的sql语句
    <select id="findByVo" parameterType="accountVo" resultType="account">
        select * from account where name like #{account.name}
    </select>

测试方法
    @Test
    public void findByVo(){
        Account cong= new Account();
        cong.setName("%on%");
        AccountVo accountVo = new AccountVo();
        accountVo.setAccount(cong);
        List<Account> accounts = mapper.findByVo(accountVo);
        for (Account account : accounts) {
            System.out.println(account.toString());
        }
    }

 2.resultType result type

Can be a simple data type, the object may be pojo, may also be set pojo

Return result is often a problem encountered is inconsistent with the attribute name attribute database table entity classes

This time can be used resultMap label will unite them, or from the mysql as an alias by keyword

2.1resultMap

    <resultMap id="accountDiy" type="account">
        <id column="id" property="aid"></id>
        <result column="name" property="aname"></result>
        <result column="money" property="amoney"></result>
    </resultMap>
    <select id="findAll" resultMap="accountDiy">
        select * from account;
    </select>

2.2 surnamed

    <select id="findById" parameterType="int"  resultType="account">
        select id as aid,name as aname,money as amoney from account where id = #{id}
    </select>

Complete project

1. Create a maven project, import the relevant dependent

<?xml version="1.0" encoding="UTF-8"?>
<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.cong</groupId>
    <artifactId>mybatis_para_res_config</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>
</project>

2. Create com.cong.pojo package, as well as two classes

package com.cong.pojo;

public class Account {
    private int aid;
    private String aname;
    private float amoney;

    @Override
    public String toString() {
        return "Account{" +
                "aid=" + aid +
                ", aname='" + aname + '\'' +
                ", amoney=" + amoney +
                '}';
    }

    public int getAid() {
        return aid;
    }

    public void setAid(int aid) {
        this.aid = aid;
    }

    public String getAname() {
        return aname;
    }

    public void setAname(String aname) {
        this.aname = aname;
    }

    public float getAmoney() {
        return amoney;
    }

    public void setAmoney(float amoney) {
        this.amoney = amoney;
    }
}




package com.cong.pojo;

public class AccountVo {
    private Account account;

    public Account getAccount() {
        return account;
    }
    public void setAccount(Account account) {
        this.account = account;
    }
}

3. Create com.cong.mapper.AccountMapper Interface

package com.cong.mapper;

import com.cong.pojo.Account;
import com.cong.pojo.AccountVo;

import java.util.List;

public interface AccountMapper {
    List<Account> findAll();
    Account findById(int id);
    List<Account> findByVo(AccountVo accountVo);
    List<Account> findByName(String name);
    void saveAccount(Account account);
}

4. Create a log4j.properties file in the resources and SqlMapConfig.xml

Here is the configuration file
 <xml Version =? " 1.0 " encoding = " UTF-8 " ?> 
<! DOCTYPE the Configuration 
        the PUBLIC " - // mybatis.org//DTD Config 3.0 // EN " 
        " http://mybatis.org /dtd/mybatis-3-config.dtd " > 
<Configuration> 
    <typeAliases> 
        <-! all classes of the package under the alias register -> 
        <package name = " com.cong.pojo " > </ package> 
    < / typeAliases> 
    <Environments default = " MySQL ">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"></property>
                <property name="url" value="jdbc:mysql://localhost:3306/cong"></property>
                <property name="username" value="root"></property>
                <property name="password" value="123456"></property>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/AccountMapper.xml"></mapper>
    </mappers>
</configuration>



下面是log4j

# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

5. Create mapper directory in the resources, and then create a file AccountMapper.xml

<? xml Version = " 1.0 " encoding = " UTF-8 " ?> 
<! DOCTYPE Mapper 
        the PUBLIC " - // mybatis.org//DTD Mapper 3.0 // EN " 
        " http://mybatis.org/dtd/mybatis mapper.dtd--3 " > 
    ! <- 
    namespace method binding interfaces dao, dao interface for the corresponding sql language name mapper in 
    reference to self: HTTP: // www.mybatis.org/mybatis-3/zh/ started.html-Getting 
    -> 
<Mapper namespace = " com.cong.mapper.AccountMapper " > 
    <The resultMap ID = "accountDiy" type="account">
        <id column="id" property="aid"></id>
        <result column="name" property="aname"></result>
        <result column="money" property="amoney"></result>
    </resultMap>
    <select id="findAll" resultMap="accountDiy">
        select * from account;
    </select>
    <select id="findById" parameterType="int"  resultType="account">
        select id as aid,name as aname,money as amoney from account where id = #{id}
    </select>
    <select id="findByName" parameterType="string"  resultMap="accountDiy">
        select * from account where name like #{name}
    </select>
    <select id="findByVo" parameterType="accountVo"  resultMap="accountDiy">
        select * from account where name like #{account.aname}
    </select>
    <insert id="saveAccount" parameterType="account">
        insert into account(name,money) VALUES (#{aname},#{amoney});
    </insert>
</mapper>

6. Test class

import com.cong.mapper.AccountMapper;
import com.cong.pojo.Account;
import com.cong.pojo.AccountVo;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

public class TestAccount {
    private InputStream inputStream;
    private SqlSession sqlSession;
    private AccountMapper mapper;
    @Test
    public void findAll(){
        List<Account> accounts = mapper.findAll();
        for (Account account : accounts) {
            System.out.println(account.toString());
        }
    }
    @Test
    public void findByName(){
        List<Account> accounts = mapper.findByName("%ong%");
        for (Account account : accounts) {
            System.out.println(account.toString());
        }
    }
    @Test
    public void findById(){
        Account account = mapper.findById(1);
        System.out.println(account.toString());
    }
    @Test
    public void findByVo(){
        Account cong = new Account();
        cong.setAname("%on%");
        AccountVo accountVo = new AccountVo();
        accountVo.setAccount(cong);
        List<Account> accounts = mapper.findByVo(accountVo);
        for (Account account : accounts) {
            System.out.println(account.toString());
        }
    }
    @Test
    public void save(){
        Account account = new Account();
        account.setAname("rainbow");
        account.setAmoney(111111);
        mapper.saveAccount(account);
    }
    @Before
    public void init() throws Exception{
        inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
        sqlSession = factory.openSession();
        mapper = sqlSession.getMapper(AccountMapper.class);
    }
    @After
    public void destroy() throws Exception{
        sqlSession.commit();
        sqlSession.close();
        inputStream.close();
    }
}

7. Complete Directory

 

Guess you like

Origin www.cnblogs.com/ccoonngg/p/11300871.html