MyBatis-环境配置以及查询

来源:互联网 发布:淘宝商家贷款条件 编辑:程序博客网 时间:2024/06/05 19:00

1.mybatis官网

https://github.com/mybatis
https://github.com/mybatis/mybatis-3/releases

2.mybatis配置文件、代码举例

需要有两个配置文件:
1)sqlMapConfig.xml配置数据源,事务等mybatis运行环境,该xml文件名可以自己定义。
2)xxxmapper.xml配置文件,配置对象sql语句映射文件,该文件名可随意定义。
以查询Student对象为例,配置数据的结构如下所示:       
├─config
│  │  log4j.properties
│  │  sqlMapConfig.xml //名称随意,在SqlSessionFactoryBuilder创建SqlSessionFactory时指定该名称即可。
│  │  
│  └─mapper
│          studentMapper.xml//名称随意,在sqlMapConfig.xml文件中指定即可。
│          
├─lib
│      cglib-3.2.2.jar
│      commons-logging-1.2.jar
│      javassist-3.20.0-GA.jar
│      log4j-1.2.17.jar
│      log4j-core-2.3.jar
│      mybatis-3.4.0.jar
│      mybatis-spring-1.3.0.jar
│      mysql-connector-java-5.1.22-bin.jar
│      ognl-3.1.2.jar
│      slf4j-api-1.7.21.jar
│      slf4j-log4j12-1.7.21.jar
│      
└─src
    └─mybatis
            MybatisTest.java
            Student.java
1)sqlMapConfig.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>  <!-- 与Spring整合后environment将不需要再配置 -->  <environments default="development">    <environment id="development">      <transactionManager type="JDBC"/>      <dataSource type="POOLED">        <property name="driver" value="com.mysql.jdbc.Driver"/>        <property name="url" value="jdbc:mysql://localhost:3306/high"/>        <property name="username" value="root"/>        <property name="password" value="1234"/>      </dataSource>    </environment>  </environments>    <mappers>    <mapper resource="mapper/studentMapper.xml"/>  </mappers></configuration>
2)xxxmapper.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="student"><!-- id可以理解为标识sql statement的唯一标识 --><!--<span style="white-space:pre"></span>MyBatis中占位符的表达方式若为简单类型,#{}中可以使用任意的形参,若复杂类型必须是xxx.属性名.属性名。resultType指定需要映射的类型。 --><select id="findStudentById" parameterType="int" resultType="mybatis.Student">select * from student where id = #{id}</select><!-- 模糊查询举例 %%在调用的地方添加 ,这样可以防止sql注入--><!-- 注意这里虽然返回时多天,但是resultType还是Student而不是List --><select id="findStudentByName" parameterType="String" resultType="mybatis.Student">select * from student where name like #{name};</select><!-- 可以使用${}进行拼接sql串,来将%%直接嵌入语句中,注意这种写法有可能发生sql注入--><!-- **注意,此时${}中只能使用形参value,而不能是任意的形参 --><select id="findStudentByName" parameterType="String" resultType="mybatis.Student">select * from student where name like '%${value}%';</select></mapper>
3)另外,由于使用了log4j用来输出log,所以需要再src目录下配置 log4j.properties 文件。
# Global logging configuration#When release DEBUG->info or ERRORlog4j.rootLogger=DEBUG, stdout# MyBatis logging configuration...log4j.logger.org.mybatis.example.BlogMapper=TRACE# Console output...log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
4)MyBatisTest.java
package mybatis;import java.io.IOException;import java.io.InputStream;import java.util.List;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;public class MybatisTest {public static void main(String[] args) throws IOException{//指定mybatis的配置文件InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml");//得到 SqlSessionFactory接口引用 用来创建SqlSession接口引用SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);//通过工厂来获取SqlSession接口SqlSession sqlSession = sqlSessionFactory.openSession();//通过 SqlSession接口 操作数据库(发出sql进行CRUD)//第一个参数 mapper中namespace.statementidint studentId = 13;Student student = (Student)sqlSession.selectOne("student.findStudentById", studentId);//注意第二个参数需要加上 % %List<Student> students = sqlSession.selectList("student.findStudentByName", "%y%");sqlSession.close();System.out.println(student);System.out.println(students);}}

3.小结

1)xxxMapper.xml文件中通过parameterType指定查询语句占位符参数的类型,resultType来指定查询结果的类型(注意不是list,而是映射类的类型)。
2)#{}标识占位符,形参名字可以任意,不会引起SQL注入。${}sql语句连接符,形参必须使用value,会引起sql注入。
3)selectOne查询一条数据,selectList查询多条数据。

<完>

0 0
原创粉丝点击