mybatis

1.基础的Mybatis+Maven工程创建

对应的pom.xml文件为

<?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.sankuai.reed</groupId>
    <artifactId>mybatis</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--不加此段则无法解析配置文件-->
 <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>
        </resources>
    </build>
    
    <dependencies>
        <!-- ibatis.jar 从网络获取,则不需要手动导入ibatis的jar包!-->
 <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.8</version>
        </dependency>

        <!-- jdbc -->
 <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.34</version>
        </dependency>

        <!-- junit.jar -->
 <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>
    </dependencies>
</project>


2.创建用户表,并插入一条测试数据

Create TABLE `user` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `userName` varchar(50) DEFAULT NULL,

  `userAge` int(11) DEFAULT NULL,

  `userAddress` varchar(200) DEFAULT NULL,

  PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

Insert INTO `user` VALUES ('1', 'summer', '100', 'shanghai,pudong');

3.设置mybatis 配置文件:Configuration.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>
<typeAliases>
    <typeAlias alias="User" type="reed.sankuai.model.User"/>
</typeAliases>

<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://127.0.0.1:3306/mybatis" />
            <property name="username" value="root"/>
            <property name="password" value="root"/>
        </dataSource>
    </environment>
</environments>
<mappers>
    <mapper resource="reed/sankuai/model/User.xml"/>
</mappers>
</configuration>



4. 建立与数据库对应的 java class,以及映射文件.

public class User {

    private int id;
    private String userName;
    private String userAge;
    private String userAddress;

        // set 和 get方法

}


User.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="reed.sankuai.model.User">
    <select id="selectUserById" parameterType="int" resultType="User">
        select * from user where id = #{id};
    </select>
</mapper>


5.编写对应的Test类

package reed.sankuai.test;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import reed.sankuai.model.User;

/**
 * Created by fanqunsong on 2017/8/21.
 */
public class Test {
    private static SqlSessionFactory sqlSessionFactory;
    private static Reader reader;
    static {
        try {
            reader = Resources.getResourceAsReader("mybatis/Configuration.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSessionFactory getSession(){
        return sqlSessionFactory;
    }

    public static void main(String[] args) {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            User user = (User)session.selectOne("reed.sankuai.model.User.selectUserById",1);
            System.out.println(user.getUserName());
            System.out.println(user.getUserAddress());
        } finally {
            session.close();
        }
    }
}


-------------------------------------------------------------------------------------------------------------------

以接口的方式编程

上面已经搭建好了mybatis,mysql,maven的环境,并且实现了一个简单的查询。请注意,这种方式是用SqlSession实例来直接执行已映射的SQL语句:
session.selectOne("reed.sankuai.model.User.selectUserById", 1)
其实还有更简单的方法,而且是更好的方法,使用合理描述参数和SQL语句返回值的接口(比如IUserOperation.class),

这样现在就可以至此那个更简单,更安全的代码,没有容易发生的字符串文字和转换的错误.下面是详细过程:

 

建立接口类IUserOperation

 

public interface IUserOperation {
    User selectUserById(int id);
}

请注意,这里面有一个方法名 selectUserByID 必须与 User.xml 里面配置的 select 的id 对应(<select id="selectUserByID")

重写测试代码

 

public static void main(String[] args) {
    SqlSession session = sqlSessionFactory.openSession();
    try {
       // User user = (User)session.selectOne("reed.sankuai.model.User.selectUserById",1);
 IUserOperation userOperation = session.getMapper(IUserOperation.class);
        User user = userOperation.selectUserById(1);
        System.out.println(user.getUserName());
        System.out.println(user.getUserAddress());
    } finally {
        session.close();
    }
}

注意:User.xml需做如下修改<mapper namespace="com.sankuai.inter.IUserOperation">

否则会报如下错误:Type interface com.sankuai.inter.IUserOperation is not known to the MapperRegistry

-------------------------------------------------------------------------------

实现增删改查

-----------------------------------------------------------------

实现关联数据的查询

在实际项目中,经常是关联表的查询,比如最常见到的多对一,一对多等。这些查询是如何处理的呢,这一讲就讲这个问题。

1.首先创建一个Article 这个表,并初始化数据.

Drop TABLE IF EXISTS `article`;

Create TABLE `article` (

  `id` int(11) NOT NULL auto_increment,

  `userid` int(11) NOT NULL,

  `title` varchar(100) NOT NULL,

  `content` text NOT NULL,

  PRIMARY KEY  (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

-- ----------------------------

-- 添加几条测试数据

-- ----------------------------

Insert INTO `article` VALUES ('1', '1', 'test_title', 'test_content');

Insert INTO `article` VALUES ('2', '1', 'test_title_2', 'test_content_2');

Insert INTO `article` VALUES ('3', '1', 'test_title_3', 'test_content_3');

Insert INTO `article` VALUES ('4', '1', 'test_title_4', 'test_content_4');

2.创建Article.java

public class Article {
    private int id;
    private User user;
    private String title;
    private String content;

// set get方法

}


3.在Configuration.xml中添加<typeAlias alias="Article"type="reed.sankuai.model.Article"/>

4.在User.xml中添加


<resultMap id="resultUserArticleList" type="Article">
    <id property="id" column="aid" />
    <result property="title" column="title" />
    <result property="content" column="content" />

    <association property="user" javaType="User">
        <id property="id" column="id" />
        <result property="userName" column="userName" />
        <result property="userAddress" column="userAddress" />
    </association>
</resultMap>

<select id="getUserArticles" parameterType="int" resultMap="resultUserArticleList">
   select user.id,user.userName,user.userAddress,article.id aid,article.title,article.content from user,article
          where user.id=article.userid and user.id=#{id}
</select>


 

 5.在IUserOperation中
List<Article> getUserArticles(int id);

6.Test.java

List<Article> articleList =userOperation.getUserArticles(1);
for(Article article:articleList){
    System.out.println(article.getId());
    System.out.println(article.getUser().getUserAddress());
    System.out.println(article.getContent());
}

------------------------------------------------------------------------------------------------------------------------------------------

mybatis与spring集成

1.导入spring所需依赖的jar包和dbcp所需要依赖的jar包

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>

<!-- mybatis spring支持 -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.2.8</version>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.0</version>
</dependency>
<!-- dbcp -->
<dependency>
    <groupId>commons-dbcp</groupId>
    <artifactId>commons-dbcp</artifactId>
    <version>1.4</version>
</dependency>

 

2.建立applicationContext.xml

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="
 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
 http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
 default-autowire="byName" default-lazy-init="false">

    <!--本示例采用DBCP连接池,应预先把DBCP的jar包复制到工程的lib目录下。 -->

 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?characterEncoding=utf8"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--dataSource属性指定要用到的连接池-->
 <property name="dataSource" ref="dataSource"/>
        <!--configLocation属性指定mybatis的核心配置文件-->
 <property name="configLocation" value="mybatis/Configuration.xml"/>
    </bean>

    <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <!--sqlSessionFactory属性指定要用到的SqlSessionFactory实例-->
 <property name="sqlSessionFactory" ref="sqlSessionFactory" />
        <!--mapperInterface属性指定映射器接口,用于实现此接口并生成映射器对象-->
 <property name="mapperInterface" value="com.sankuai.inter.IUserOperation" />
    </bean>

</beans>

这里面的重点就是 org.mybatis.spring.SqlSessionFactoryBean 与 org.mybatis.spring.mapper.MapperFactoryBean[b] 实现了 spring  的接口,并产生对象。

5.测试代码SpringMybatisTest.java

public class MybatisSpringTest {

    private static ApplicationContext ctx;
    static {
        ctx = new ClassPathXmlApplicationContext("spring/applicationContext.xml");
    }

    public static void main(String[] args) {
        IUserOperation mapper =(IUserOperation)ctx.getBean("userMapper");
        //测试id=1的用户查询,根据数据库中的情况,可以改成你自己的.
 System.out.println("得到用户id=1的用户信息");
        User user = mapper.selectUserById(1);
        System.out.println(user.getUserAddress());

        //得到文章列表测试
 System.out.println("得到用户id为1的所有文章列表");
        List<Article> articles = mapper.getUserArticles(1);

        for(Article article:articles){
            System.out.println(article.getContent()+"--"+article.getTitle());
        }
    }
}

--------------------------------------------------------------------------------------------

与springmvc整合

1. web.xml 配置 spring dispatchservlet ,比如为:mvc-dispatcher
2. mvc-dispatcher-servlet.xml 文件配置
3. spring applicationContext.XML文件配置(与数据库相关,与mybatis sqlSessionFaction 整合,扫描所有mybatis mapper 文件等.)
4. 编写controller 类

1. web.xml 配置 spring dispatchservlet

<context-param>

    <param-name>contextConfigLocation</param-name>

    <param-value>classpath*:config/applicationContext.xml</param-value>

  </context-param>

  <listener>

    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

  </listener>

  <listener>

    <listener-class>

            org.springframework.web.context.ContextCleanupListener</listener-class>

  </listener>

  <servlet>

    <servlet-name>mvc-dispatcher</servlet-name>

    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

    <load-on-startup>1</load-on-startup>

  </servlet>

  <servlet-mapping>

    <servlet-name>mvc-dispatcher</servlet-name>

    <url-pattern>/</url-pattern>

  </servlet-mapping>

2. 在web.xml 同目录下配置 mvc-dispatcher-servlet.xml 文件,这个文件名前面部分必须与你在web.xml里面配置的DispatcherServlet 的servlet名字对应.其内容为:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:config/applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <listener>
    <listener-class>
            org.springframework.web.context.ContextCleanupListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

2. 在web.xml 同目录下配置 mvc-dispatcher-servlet.xml 文件,这个文件名前面部分必须与你在web.xml里面配置的DispatcherServlet 的servlet名字对应.其内容为:

程序代码 程序代码


<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans    
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <context:component-scan base-package="com.yihaomen.controller" />
    <mvc:annotation-driven />
   
    <mvc:resources mapping="/static/**" location="/WEB-INF/static/"/> 
    <mvc:default-servlet-handler/> 
    
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
< /beans>

3.spring 配置文件 applicationContext.xml

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?characterEncoding=utf8"/>
    <property name="username" value="root"/>
    <property name="password" value="root"/>
</bean>

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <!--dataSource属性指定要用到的连接池-->
 <property name="dataSource" ref="dataSource"/>
    <!--configLocation属性指定mybatis的核心配置文件-->
 <property name="configLocation" value="mybatis/Configuration.xml"/>
</bean>

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>

<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
    <!--sqlSessionFactory属性指定要用到的SqlSessionFactory实例-->
 <property name="sqlSessionFactory" ref="sqlSessionFactory" />
    <!--mapperInterface属性指定映射器接口,用于实现此接口并生成映射器对象-->
 <property name="mapperInterface" value="com.sankuai.inter.IUserOperation" />
</bean>

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.sankuai.inter" />
</bean>
4.编写controller层

@Controller

@RequestMapping("/article")

public class UserController {

    @Autowired

    IUserOperation userMapper;

 

    @RequestMapping("/list")

    public ModelAndView listall(HttpServletRequest request,HttpServletResponse response){

        List<Article> articles=userMapper.getUserArticles(1);

        ModelAndView mav=new ModelAndView("list");

        mav.addObject("articles",articles);

        return mav;

    }

}

http://localhost:8080/Maven_Test/article/list

----------------------------------------------------------------------------------

mybatis 动态sql语句

mybatis 的动态sql语句是基于OGNL表达式的。可以方便的在 sql 语句中实现某些逻辑. 总体说来mybatis 动态SQL 语句主要有以下几类:
1. if 语句 (简单的条件判断)
2. choose (when,otherwize) ,相当于java 语言中的 switch ,与 jstl 中的choose 很类似.
3. trim (对包含的内容加上 prefix,或者 suffix 等,前缀,后缀)
4. where (主要是用来简化sql语句中where条件判断的,能智能的处理 and or ,不必担心多余导致语法错误)
5. set (主要用于更新时)
6. foreach (在实现 mybatis in 语句查询时特别有用)
下面分别介绍这几种处理方式
mybaits if 语句处理
 

<select id="dynamicIfTest" parameterType="Blog" resultType="Blog">

 

        select * from t_blog where 1 = 1

 

        <if test="title != null">

 

            and title = #{title}

 

        </if>

 

        <if test="content != null">

 

            and content = #{content}

 

        </if>

 

        <if test="owner != null">

 

            and owner = #{owner}

 

        </if>

 

    </select>


这条语句的意思非常简单,如果你提供了title参数,那么就要满足title=#{title},同样如果你提供了Content和Owner的时候,它们也需要满足相应的条件,之后就是返回满足这些条件的所有Blog,

这是非常有用的一个功能,以往我们使用其他类型框架或者直接使用JDBC的时候, 如果我们要达到同样的选择效果的时候,我们就需要拼SQL语句,这是极其麻烦的,比起来,上述的动态SQL就要简单多了

2.2. choose (when,otherwize) ,相当于java 语言中的 switch ,与 jstl 中的choose 很类似

 

<select id="dynamicChooseTest" parameterType="Blog" resultType="Blog">

 

        select * from t_blog where 1 = 1

 

        <choose>

 

            <when test="title != null">

 

                and title = #{title}

 

            </when>

 

            <when test="content != null">

 

                and content = #{content}

 

            </when>

 

            <otherwise>

 

                and owner = "owner1"

 

            </otherwise>

 

        </choose>

 

    </select>

when元素表示当when中的条件满足的时候就输出其中的内容,跟JAVA中的switch效果差不多的是按照条件的顺序,当when中有条件满足的时候,就会跳出choose,

即所有的when和otherwise条件中,只有一个会输出,当所有的我很条件都不满足的时候就输出otherwise中的内容。所以上述语句的意思非常简单,

当title!=null的时候就输出and titlte = #{title},不再往下判断条件,当title为空且content!=null的时候就输出and content = #{content},当所有条件都不满足的时候就输出otherwise中的内容。

3.trim (对包含的内容加上 prefix,或者 suffix 等,前缀,后缀)

 

<select id="dynamicTrimTest" parameterType="Blog" resultType="Blog">

 

        select * from t_blog

 

        <trim prefix="where" prefixOverrides="and |or">

 

            <if test="title != null">

 

                title = #{title}

 

            </if>

 

            <if test="content != null">

 

                and content = #{content}

 

            </if>

 

            <if test="owner != null">

 

                or owner = #{owner}

 

            </if>

 

        </trim>

 

    </select>

 

trim元素的主要功能是可以在自己包含的内容前加上某些前缀,也可以在其后加上某些后缀,与之对应的属性是prefix和suffix;可以把包含内容的首部某些内容覆盖,

即忽略,也可以把尾部的某些内容覆盖,对应的属性是prefixOverrides和suffixOverrides;正因为trim有这样的功能,所以我们也可以非常简单的利用trim来代替where元素的功能

4. where (主要是用来简化sql语句中where条件判断的,能智能的处理 and or 条件

 

<select id="dynamicWhereTest" parameterType="Blog" resultType="Blog">

 

        select * from t_blog

 

        <where>

 

            <if test="title != null">

 

                title = #{title}

 

            </if>

 

            <if test="content != null">

 

                and content = #{content}

 

            </if>

 

            <if test="owner != null">

 

                and owner = #{owner}

 

            </if>

 

        </where>

 

    </select>

where元素的作用是会在写入where元素的地方输出一个where,另外一个好处是你不需要考虑where元素里面的条件输出是什么样子的,MyBatis会智能的帮你处理,

如果所有的条件都不满足那么MyBatis就会查出所有的记录,如果输出后是and 开头的,MyBatis会把第一个and忽略,当然如果是or开头的,MyBatis也会把它忽略;

此外,在where元素中你不需要考虑空格的问题,MyBatis会智能的帮你加上。像上述例子中,如果title=null, 而content != null,

那么输出的整个语句会是select * from t_blog where content = #{content},而不是select * from t_blog where and content = #{content},因为MyBatis会智能的把首个and 或 or 给忽略。

5.set (主要用于更新时)

 

<update id="dynamicSetTest" parameterType="Blog">

 

        update t_blog

 

        <set>

 

            <if test="title != null">

 

                title = #{title},

 

            </if>

 

            <if test="content != null">

 

                content = #{content},

 

            </if>

 

            <if test="owner != null">

 

                owner = #{owner}

 

            </if>

 

        </set>

 

        where id = #{id}

 

    </update>

set元素主要是用在更新操作的时候,它的主要功能和where元素其实是差不多的,主要是在包含的语句前输出一个set,然后如果包含的语句是以逗号结束的话将会把该逗号忽略,

如果set包含的内容为空的话则会出错。有了set元素我们就可以动态的更新那些修改了的字段


全部评论

相关推荐

拉丁是我干掉的:把上海理工大学改成北京理工大学。成功率增加200%
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务