接上篇:Mybatis环境搭建

在搭建环境时已经有了mapper和sqlMapConfig

1,数据库建表

 

prompt PL/SQL Developer import file
prompt Created on 2018年6月1日 by Administrator
set feedback off
set define off
prompt Creating T_USER...
create table T_USER
(
  T_NAME VARCHAR2(10) not null,
  T_PASS VARCHAR2(10),
  T_ID   VARCHAR2(10)
)
;

prompt Deleting T_USER...
delete from T_USER;
commit;
prompt Loading T_USER...
insert into T_USER (T_NAME, T_PASS, T_ID)
values ('张三', 'zhangsan', null);
insert into T_USER (T_NAME, T_PASS, T_ID)
values ('王五', 'wangwu', null);
insert into T_USER (T_NAME, T_PASS, T_ID)
values ('小张', 'xiaozhang', null);
insert into T_USER (T_NAME, T_PASS, T_ID)
values ('刘雯2', 'liuwen2', null);
insert into T_USER (T_NAME, T_PASS, T_ID)
values ('刘雯', 'liuwen', null);
insert into T_USER (T_NAME, T_PASS, T_ID)
values ('王二麻子', 'wanger', null);
insert into T_USER (T_NAME, T_PASS, T_ID)
values ('刘雯1', 'liuwen1', null);
insert into T_USER (T_NAME, T_PASS, T_ID)
values ('刘雯3', 'liuwen3', null);
insert into T_USER (T_NAME, T_PASS, T_ID)
values ('王柳', 'liu', null);
insert into T_USER (T_NAME, T_PASS, T_ID)
values ('Jone', 'Jone', null);
insert into T_USER (T_NAME, T_PASS, T_ID)
values ('李四', 'lisi', null);
commit;
prompt 11 records loaded
set feedback on
set define on
prompt Done.

 

2,导包

3,编写POJO

package com.songyan.pojo;

public class Customer {
    private Integer id;      //主键id
    private String username; //客户名称
    private String job;      //职业
    private String phone;    //电话
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getJob() {
        return job;
    }
    public void setJob(String job) {
        this.job = job;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    
    
    @Override
    public String toString() {
        // 
        return "Customer [id=" + id + ",username=" + username + ",job=" + job + ",phone=" + phone + "]";
    }
    
    
}

3,与之对应的mapper

<?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.songyan.mapper.Customer">
    <select id="findCustomerById" parameterType="Integer"
        resultType="com.songyan.pojo.Customer">
        select * from tb_customer where id = #{v}
    </select>
    <select id="findCustomerByName" parameterType="Integer"
        resultType="com.songyan.pojo.Customer">
        select * from tb_customer where username like '%${value}%'
    </select>
</mapper>

4,applicationcontext.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--配置环境,默认的环境id为oracle -->
    <environments default="oracle">
        <!-- 配置环境为oracle的环境 -->
        <environment id="oracle">
            <!--使用JDBC的事务处理 -->
            <transactionManager type="JDBC" />
            <!--数据库连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="oracle.jdbc.driver.OracleDriver"></property>
                <property name="url" value="jdbc:oracle:thin:@localhost:1521:inspur"></property>
                <property name="username" value="scott"></property>
                <property name="password" value="tiger"></property>
            </dataSource>
        </environment>
    </environments>
    <!--配置mapper的位置 -->
    <mappers>
        <mapper resource="com/songyan/mapper/Customer.xml" />
    </mappers>
</configuration>

log4j.properties

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p [%t] %c{1}:%L - %m%n
#\u5728\u5F00\u53D1\u73AF\u5883\u4E0B\u65E5\u5FD7\u7EA7\u522B\u8981\u8BBE\u7F6E\u6210DEBUG\uFF0C\u751F\u4EA7\u73AF\u5883\u8BBE\u7F6E\u6210info\u6216error
log4j.rootLogger=DEBUG, stdout
#log4j.rootLogger=stdout

5,测试类

package com.songyan.client;

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

import javax.faces.application.Application;
import javax.jms.Session;

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.Test;

import com.songyan.pojo.Customer;

public class Test1 {
    /**
     * 根据用户编号查询客户信息
     * @throws IOException 
     */
    @Test 
    public void selectCuById() throws IOException
    {
        //读取配置信息
        String resource="applicationContext.xml";
        //根据配置文件构建sqlsessionFactory
        InputStream in=Resources.getResourceAsStream(resource);
        //通过sqlsessionFactory创建sqlsession
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(in);
        SqlSession sqlSession =sqlSessionFactory.openSession(); 
        //sqlsession执行sql并返回执行结果
        Customer customer= sqlSession.selectOne("com.songyan.mapper.Customer.findCustomerById",1);
        //打印输出结果
        System.out.println(customer);
        //关闭sqlsession
        sqlSession.close();
    }
    
    /**
     * 根据用户名查询客户信息
     * @throws IOException 
     */
    @Test
    public void findCustomerByName() throws IOException
    {
        //加载配置信息
        String resource="applicationContext.xml";
        //获取输入流
        InputStream in=Resources.getResourceAsStream(resource);
        //获取工厂
        SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(in);
        //获取sqlsession对象
        SqlSession sqlSession=sessionFactory.openSession();
        
        //执行sql
        List<Customer> customers=sqlSession.selectList("com.songyan.mapper.Customer.findCustomerByName","j");
        //输出结果
        for(Customer cu : customers)
        {
            System.out.println(cu);
        }
        //关闭sqlsession
        sqlSession.close();
        
    }
    
    
    
}

根据客户id查询的结果

根据客户name查询的结果

#{} 表示占位符,可以防止sql注入的问题,在执行sql的之后会自动补充单引号,他的参数可以任意的

${} 表示字符串的拼接 不可以防止sql的诸注入问题,在执行sql 的时候也没有任何添加符号,他的符号只能是value

当需要使用模糊查询,还要防止sql注入的时候可以使用下面的方式:

select * from user where username like "%"#{haha}"%"

使用#{}实现防止sql注入的问题

使用like "%"#{haha}"%"实现模糊查询

他表示的是包含haha的字段

 

 

 

 


posted on 2018-06-05 08:13  song.yan  阅读(1617)  评论(0编辑  收藏  举报