当前位置: 代码迷 >> Web前端 >> MyBatis(iBatis 三)入门示例 及 整合Mybatis与Spring3
  详细解决方案

MyBatis(iBatis 三)入门示例 及 整合Mybatis与Spring3

热度:1253   发布时间:2012-09-19 13:43:53.0
MyBatis(iBatis 3)入门示例 及 整合Mybatis与Spring3

?

以前的iBatis 项目在2010 年5 月,将代码库迁致Google Code,并更名为MyBatis。

本示例用的是ibatis-3-core-3.0.0.208.zip,首先加如mybatis和mysql数据库的jar包。

?

table.sql

?

create database mybatis;  
use mybatis;  
create table user(  
    id int primary key auto_increment,  
    name varchar(50)  
);  
insert into user values(null,'张三'); 
?

?

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="com.nantian.mybatis.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="com/nantian/mybatis/model/UserMapper.xml"/>  
    </mappers>  
</configuration>  
?

?

DBUtil

?

package com.nantian.mybatis.data;  
  
import java.io.IOException;  
import java.io.Reader;  
  
import org.apache.ibatis.io.Resources;  
import org.apache.ibatis.session.SqlSessionFactory;  
import org.apache.ibatis.session.SqlSessionFactoryBuilder;  
  
public class DBUtil {  
    private static final DBUtil dbUtil = new DBUtil();  
    private SqlSessionFactory sqlSessionFactory = null;  
  
    private DBUtil() {  
        try {  
            String resource = "com/nantian/mybatis/data/configuration.xml";  
            Reader reader = Resources.getResourceAsReader(resource);  
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);  
            reader.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
  
    public static DBUtil getInstance() {  
        return dbUtil;  
    }  
  
    public SqlSessionFactory getSqlSessionFactory() {  
        return sqlSessionFactory;  
    }  
}  
?

?

User

?

package com.nantian.mybatis.model;  
  
public class User {  
    private int id;  
    private String name;  
  
    public int getId() {  
        return id;  
    }  
  
    public void setId(int id) {  
        this.id = id;  
    }  
  
    public String getName() {  
        return name;  
    }  
  
    public void setName(String name) {  
        this.name = name;  
    }  
}  
?

?

UserMapper

?

package com.nantian.mybatis.model;  
  
public interface UserMapper {  
    public User selectUser(int id);  
}  
?

?

?

UserMapper.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="com.nantian.mybatis.model.UserMapper">  
    <select id="selectUser" parameterType="int" resultType="User">  
        select id,name from user where id = #{id}  
    </select>  
</mapper>  
?

?

Test

?

package com.nantian.mybatis.test;  
  
import junit.framework.TestCase;  
  
import org.apache.ibatis.session.SqlSession;  
  
import com.nantian.mybatis.data.DBUtil;  
import com.nantian.mybatis.model.User;  
import com.nantian.mybatis.model.UserMapper;  
  
public class Test extends TestCase {  
    public void selectUser() {  
        SqlSession sqlSession = DBUtil.getInstance().getSqlSessionFactory()  
                .openSession();  
        try {  
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);  
            User user = userMapper.selectUser(1);  
            System.out.println(user.getName());  
        } finally {  
            sqlSession.close();  
        }  
    }  
}  
?

?

Mybatis3可以使用注解了。注解是非常简单明了的,但是JAVA 注解既有局限性,在语句比较复杂的情况下又比较容易混乱。所以,如果你的语句比较复杂,最好还是使用XML 来映射语句。这主要取决于你和你的项目团队,决定哪个更适合于你,主要还是以稳健为主。也就是说,你不需要制约于哪一种方式,你可以很容易的把注解转为XML,也可以把XML 转化为注解。

?

?

?

?

整合Mybatis与Spring3

http://www.iteye.com/topic/1018134

?

1.实体bean?

Java代码? ?收藏代码
  1. package?org.hyn.bean;??
  2. ??
  3. public?class?User?{??
  4. ????private?int?id;??
  5. ????private?String?name;??
  6. ????private?int?age;??
  7. ...//长长的set?get?方法??



2.Mapper及配置文件

Java代码? ?收藏代码
  1. package?org.hyn.maper;??
  2. ??
  3. import?org.hyn.bean.User;??
  4. ??
  5. public?interface?UserMapper?{??
  6. ????public?void?insertUser(User?user);??
  7. ??
  8. ????public?User?getUser(String?name);??
  9. }??

?

Java代码? ?收藏代码
  1. <?xml?version="1.0"?encoding="UTF-8"??>???
  2. ????<!DOCTYPE?mapper???
  3. ????????PUBLIC?"-//mybatis.org//DTD?Mapper?3.0//EN"???
  4. ????????"http://mybatis.org/dtd/mybatis-3-mapper.dtd">??
  5. ??
  6. <mapper?namespace="org.hyn.maper.UserMapper">??
  7. ????<insert?id="insertUser"?parameterType="org.hyn.bean.User">??
  8. ????????insert?into?user(name,age)?values(#{name},#{age})???
  9. ????????</insert>??
  10. ????<select?id="getUser"?resultType="org.hyn.bean.User"??
  11. ????????parameterType="java.lang.String">??
  12. ????????select?*?from?user?where?name=#{name}???
  13. ???????</select>??
  14. ??
  15. ????<!--?当使用该Mybatis与Spring整合的时候,该文件必须和相应的Mapper接口文件同名,并在同一路径下?-->??
  16. </mapper>???


3.spring配置文件

Java代码? ?收藏代码
  1. <bean?id="sqlSessionFactory"?class="org.mybatis.spring.SqlSessionFactoryBean">??
  2. ????<property?name="dataSource"?ref="myDataSource"?/>??
  3. ??
  4. ????<!--?<property?name="configLocation"?value=""/>?-->??
  5. ????<!--??
  6. ????????该属性用来指定MyBatis的XML配置文件路径,跟Spring整合时,编写MyBatis映射文件的目的无非是配置一下typeAlias、setting之类的元素。不用在其中指定数据源,或者事务处理方式。就算配置了也会被忽略。因为这些都是使用Spring中的配置 ?
  7. ????????。当然如果你不打算添加typeAlias?之类的设置的话,你连MyBatis的配置文件都不用写,更不用配置这个属性了??
  8. ????-->??
  9. ??
  10. ????<!--<property?name="mapperLocations"?value="src/UserMapper.xml"/>-->??
  11. ????<!--?该配置文件用来指定Mapper映射文件的位置?,如果映射文件与相应的接口同名,且在同一路径下,那么可以不配置该选项-->??
  12. </bean>??
  13. ??
  14. <!-- ?注册Mapper方式一?
  15. <bean?id="userMapper"?class="org.mybatis.spring.mapper.MapperFactoryBean">?
  16. ? ? <property name="mapperInterface"?value="org.hyn.maper.UserMapper"/>?
  17. ? ? <property?name="sqlSessionFactory"?ref="sqlSessionFactory"/>?
  18. </bean> ?
  19. -->??
  20. ??
  21. <!--?注册Mapper方式二:也可不指定特定mapper,而使用自动扫描包的方式来注册各种Mapper?,配置如下:-->??
  22. <bean?class="org.mybatis.spring.mapper.MapperScannerConfigurer">??
  23. ????<property?name="basePackage"?value="org.hyn.maper"?/>??
  24. </bean>??


4.测试类

Java代码? ?收藏代码
  1. @Test??
  2. public?void?testGetUser()?{??
  3. ????ApplicationContext?aContext?=?new?FileSystemXmlApplicationContext("WebRoot/WEB-INF/applicationContext.xml");??
  4. ????UserMapper?userMapper?=?aContext.getBean(UserMapper.class);??
  5. ????User?user?=?userMapper.getUser("张三");??
  6. ????System.out.println(user.toString());??
  7. }??
  8. ??
  9. @Test??
  10. public?void?testAddUser(){??
  11. ????ApplicationContext?aContext?=?new?FileSystemXmlApplicationContext("WebRoot/WEB-INF/applicationContext.xml");??
  12. ????UserMapper?userMapper?=?aContext.getBean(UserMapper.class);??
  13. ????User?user?=?new?User();??
  14. ????user.setName("张三");??
  15. ????user.setAge(18);??
  16. ????userMapper.insertUser(user);??
  17. ????System.out.println("添加成功");??
  18. }??

?

?

?

?

下面付上源代码

?

?

?

mybatis mapper pojo的两种方式

?

1.如果数据库和pojo的属性名都一样的话可以用如下方式:

<select id="getUser" resultType="org.guarx.domain.User" parameterType="java.lang.String">
      <![CDATA[select * from users where id=#{value}]]>
</select>
<select id="getUsers" resultType="org.guarx.domain.User">
      <![CDATA[select * from users]]>
</select>
?

?

2.如果数据库columns name和pojo的属性名称不一样(大多数情况下)

(1)第一种方式:

?

<select id="getUsers" resultType="org.guarx.domain.User">
        <![CDATA[select t_id as id,t_username as name,t_desc as description from users]]>
</select>
?

?

(2)第二种方式:

?

<resultMap type="org.guarx.domain.User" id="userMapper">
        <result column="t_id" property="id"/>
        <result column="t_username" property="username"/>
        <result column="t_desc" property="description"/>
</resultMap>

<select id="getAll" resultMap="userMapper">
        <![CDATA[select id,username,description from users ]]>
</select>
?

?

?

?

?

?

?

?

?

?

  相关解决方案