MyBatis Study (iv)

Source: Internet
Author: User

Video View Address: Http://edu.51cto.com/course/14674.html?source=so

1. mapper.xml file 1.1, INSERT, UPDATE, delete, select
<!--     id:保證唯一    resultMap和resultType只能2选其一    parameterType:参数类型(基本数据类型、pojo、HashMap)  -->  <select id="selectUserById" parameterType="" resultMap="" resultType="User">    select userid,user_name as userName,age,pwd,sex,birthday from tb_user where userid = #{userid}  </select>
1.2. Resultmap Elements

Solve the problem of inconsistent database field names and Java attribute names using Resultmap first

Modify the Mapper.xml file

<resultMap type="User" id="UserMap" autoMapping="true">    <!-- id表示主键,必须设置          column:数据库列名称         property:实体类中的属性名    -->    <id column="userid" property="userid"/>    <result column="user_name" property="userName"/>  </resultMap>  <select id = "selectAll" resultMap="UserMap">    select *     from tb_user  </select>

To test perfect, the hump is named close

<settings>        <setting name="mapUnderscoreToCamelCase" value="false"/></settings>

Log file

DEBUG - Opening JDBC ConnectionDEBUG - Created connection 25899648.DEBUG - Setting autocommit to false on JDBC Connection [[email protected]]DEBUG - ==>  Preparing: select * from tb_user DEBUG - ==> Parameters: DEBUG - <==      Total: 5User [userid=8, userName=阿珂, pwd=123456, age=18, sex=女, birthday=Mon Aug 13 14:06:14 CST 2018]User [userid=2, userName=张三, pwd=123456, age=10, sex=男, birthday=Mon Aug 13 10:07:55 CST 2018]User [userid=3, userName=李四, pwd=123456, age=10, sex=男, birthday=Mon Aug 13 10:07:55 CST 2018]User [userid=4, userName=王五, pwd=123456, age=10, sex=男, birthday=Mon Aug 13 10:07:55 CST 2018]User [userid=5, userName=赵六, pwd=123456, age=10, sex=男, birthday=Mon Aug 13 10:07:55 CST 2018]DEBUG - Resetting autocommit to true on JDBC Connection [[email protected]]DEBUG - Closing JDBC Connection [[email protected]]DEBUG - Returned connection 25899648 to pool.

To summarize: Resolve the database name and attribute name consistent solution:

1. Aliases

2. Hump naming

3.resultMap

1.3. Get self-growing ID elements

Modify the Mapper.xml file

 <!--         useGeneratedKeys:将生成的id返回给java对象        keyColumn:主键列        keyProperty:主键的属性(业务属性)  -->  <insert id="insertUser" parameterType="User" useGeneratedKeys="true" keyColumn="userid" keyProperty="userid">    insert into tb_user(userid,user_name,age,pwd,sex,birthday)    values(seq_user.nextval,#{userName},#{age},#{pwd},#{sex},#{birthday})  </insert>

In the test code

@Test    public void testInsertUser() {        User vo = new User("阿珂3", "123456", 18, "女", new Date());        try {            userMapper.insertUser(vo);            //提交事务            sqlSession.commit();            System.out.println(vo.getUserid());        } catch (Exception e) {            e.printStackTrace();            sqlSession.rollback();        }    }

Test log

DEBUG - Opening JDBC ConnectionDEBUG - Created connection 1434803926.DEBUG - Setting autocommit to false on JDBC Connection [[email protected]]DEBUG - ==>  Preparing: insert into tb_user(userid,user_name,age,pwd,sex,birthday) values(seq_user.nextval,?,?,?,?,?) DEBUG - ==> Parameters: 阿珂3(String), 18(Integer), 123456(String), 女(String), 2018-08-13 14:57:50.296(Timestamp)DEBUG - <==    Updates: 1DEBUG - Committing JDBC Connection [[email protected]]10DEBUG - Resetting autocommit to true on JDBC Connection [[email protected]]DEBUG - Closing JDBC Connection [[email protected]]DEBUG - Returned connection 1434803926 to pool.
2, Parameter Pass 2.1, #{} Way

When there are multiple arguments, we can use the natural number, or the Pojo object

Mode one: Using natural number transfer

Requirements: Query data according to the user's name and age

1. Add a method

public List<User> queryByNameAndAge(String name,int age) throws Exception;

2. Writing mapper.xml files

 <select id="queryByNameAndAge" resultMap="UserMap">        select * from tb_user where user_name like #{0} and age =#{1}  </select>

3. Execute test Code

@Test    public void testQueryByNameAndAge() throws Exception{        List<User> list = userMapper.queryByNameAndAge("%阿%", 18);        for (User user : list) {            System.out.println(user);        }    }

Log file

DEBUG - Opening JDBC ConnectionDEBUG - Created connection 707919597.DEBUG - Setting autocommit to false on JDBC Connection [[email protected]]DEBUG - ==>  Preparing: select * from tb_user where user_name like ? and age =? DEBUG - ==> Parameters: %阿%(String), 18(Integer)DEBUG - <==      Total: 3User [userid=8, userName=阿珂, pwd=123456, age=18, sex=女, birthday=Mon Aug 13 14:06:14 CST 2018]User [userid=9, userName=阿珂2, pwd=123456, age=18, sex=女, birthday=Mon Aug 13 14:56:45 CST 2018]User [userid=10, userName=阿珂3, pwd=123456, age=18, sex=女, birthday=Mon Aug 13 14:57:50 CST 2018]DEBUG - Resetting autocommit to true on JDBC Connection [[email protected]]DEBUG - Closing JDBC Connection [[email protected]31feed]DEBUG - Returned connection 707919597 to pool.

It can actually be passed with Param, but Param starts at 1 when it's passed.

Modify Mapper.xml

 <select id="queryByNameAndAge" resultMap="UserMap">        select * from tb_user where user_name like #{param1} and age =#{param2}  </select>

But the above method is actually not very readable, we can generally use the form of annotations:

Method Two: Passing discrete parameters in the form of annotations

The declaration of the interface is as follows

public List<User> queryByNameAndAge(@Param("name")String name,@Param("age")int age) throws Exception;

The Mapper.xml file can be written as follows

 <select id="queryByNameAndAge" resultMap="UserMap">        select * from tb_user where user_name like #{name} and age =#{age}  </select>

Method Three: Pass a Pojo object directly

1, first create a Query object, which encapsulates the parameters required by the query

package cn.org.kingdom.pojo;import java.io.Serializable;public class QueryUser implements Serializable {    private String name ;     private int age ;    public QueryUser() {        super();    }    public QueryUser(String name, int age) {        super();        this.name = name;        this.age = age;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    } }

2. Writing interface methods

public List<User> queryByPojo(QueryUser  vo) throws Exception;

3. Writing mapper.xml files

<select id = "queryByPojo" parameterType="QueryUser" resultMap="UserMap">     select * from tb_user where user_name like #{name} and age =#{age}  </select>

4. Testing

@Test    public void testQueryByNameAndAge2() throws Exception{        QueryUser vo = new QueryUser("%阿%", 18);        List<User> list = userMapper.queryByPojo(vo);        for (User user : list) {            System.out.println(user);        }    }

Summary: Under normal circumstances in the development, will be preferred to select annotations and Pojo way to develop, about the natural number of the way, we understand can

2.2, ${} mode

Demand:

The database has two identical tables. History table, current table

Query the information in the table, sometimes from the history table to query the data, sometimes need to go to the new table to query the data.

You want to use 1 methods to complete an operation

interface method definition

public List<User> queryByTableName(@Param("tableName")String tableName) throws Exception;

Mapper.xml file definition

<select id= "queryByTableName" resultMap="UserMap">    select * from #{tableName}  </select>

Test class Code

@Test    public void testQuerybyTableName() throws Exception{        List<User> list = userMapper.queryByTableName("tb_user_hi");        for (User user : list) {            System.out.println(user);        }    }

Run:

Org.apache.ibatis.exceptions.PersistenceException: # # # Error querying database.  cause:java.sql.sqlexception:ora-00903: Invalid table name # # # The error exist in cn/org/kingdom/mapper/usermapper.xml### the error May involve defaultparametermap### the error occurred and setting parameters### Sql:select * from? # # Cause:java.sql . sqlexception:ora-00903: Invalid table name at Org.apache.ibatis.exceptions.ExceptionFactory.wrapException (Exceptionfactory.java : +) at Org.apache.ibatis.session.defaults.DefaultSqlSession.selectList (defaultsqlsession.java:111) at Org.apache.ibatis.session.defaults.DefaultSqlSession.selectList (defaultsqlsession.java:102) at Org.apache.ibatis.binding.MapperMethod.executeForMany (mappermethod.java:119) at Org.apache.ibatis.binding.MapperMethod.execute (mappermethod.java:63) at Org.apache.ibatis.binding.MapperProxy.invoke (mapperproxy.java:52) at Com.sun.proxy. $Proxy 4.queryByTableName ( Unknown Source) at Cn.org.kingdom.test.MyBatisTest01.testQuerybyTableName (Mybatistest01.java:120) at Sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at sun.reflect.NativeMethodAccess Orimpl.invoke (Unknown source) at Sun.reflect.DelegatingMethodAccessorImpl.invoke (Unknown source) at Java.lang.reflec T.method.invoke (Unknown Source) at Org.junit.runners.model.frameworkmethod$1.runreflectivecall (    frameworkmethod.java:47) at Org.junit.internal.runners.model.ReflectiveCallable.run (reflectivecallable.java:12) At org.junit.runners.model.FrameworkMethod.invokeExplosively (frameworkmethod.java:44) at Org.junit.internal.runners.statements.InvokeMethod.evaluate (invokemethod.java:17) at Org.junit.internal.runners.statements.RunBefores.evaluate (runbefores.java:26) at Org.junit.internal.runners.statements.RunAfters.evaluate (runafters.java:27) at Org.junit.runners.ParentRunner.runLeaf (parentrunner.java:271) at org.junit.runners.blockjunit4cla*** Unner.runchild (blockjunit4cla***unner.java:70) at Org.junit.runners.blockjunit4cla***unneR.runchild (blockjunit4cla***unner.java:50) at Org.junit.runners.parentrunner$3.run (ParentRunner.java:238) at Org.junit.runners.parentrunner$1.schedule (parentrunner.java:63) at Org.junit.runners.ParentRunner.runChildren ( parentrunner.java:236) at org.junit.runners.parentrunner.access$000 (parentrunner.java:53) at Org.junit.runners.parentrunner$2.evaluate (parentrunner.java:229) at Org.junit.runners.ParentRunner.run ( parentrunner.java:309) at Org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run ( JUNIT4TESTREFERENCE.JAVA:50) at Org.eclipse.jdt.internal.junit.runner.TestExecution.run (testexecution.java:38) at Org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests (remotetestrunner.java:467) at Org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests (remotetestrunner.java:683) at Org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run (remotetestrunner.java:390) at Org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main (remotetestrunner.java:197) 

Found a problem, actually #{} way through? In the form of passing parameters? It does not support TableName

Change #{} to ${}

<select id= "queryByTableName" resultMap="UserMap">    select * from ${tableName}  </select>

Run again

DEBUG - Opening JDBC ConnectionDEBUG - Created connection 1891119713.DEBUG - Setting autocommit to false on JDBC Connection [[email protected]]DEBUG - ==>  Preparing: select * from tb_user_hi DEBUG - ==> Parameters: DEBUG - <==      Total: 2User [userid=2, userName=张三, pwd=123456, age=10, sex=男, birthday=Mon Aug 13 10:07:55 CST 2018]User [userid=3, userName=李四, pwd=123456, age=10, sex=男, birthday=Mon Aug 13 10:07:55 CST 2018]DEBUG - Resetting autocommit to true on JDBC Connection [[email protected]]DEBUG - Closing JDBC Connection [[email protected]]DEBUG - Returned connection 1891119713 to pool.

Summarize:

#{}: Represents the parameter part of SQL, in fact the underlying is using PreparedStatement

${}: Represents string concatenation, in fact the statement object used at the bottom

can use #{} place can use ${} instead, but can use ${} where not necessarily can be replaced with #{}

MyBatis Study (iv)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.