mybatis解析--转载

来源:互联网 发布:matlab矩阵元素运算 编辑:程序博客网 时间:2024/06/09 22:16



转载http://www.cnblogs.com/wushiqi54719880/archive/2011/07/26/2117601.html

本文主要介绍了如何使用mybatis进行简单的数据库操作。本人使用的是mybatis3.05。

Mybatics 是apache 开源项目的一个数据持久层框架,其包括sql maper(sql 映射)以及 Data access object的内容。我们将通过以下示例来讲解mybatics 的相关内容。

1.创建数据库表(User表)
复制代码
CREATE TABLE `NewTable` (`userId`  bigint(20) NOT NULL AUTO_INCREMENT ,`userName`  varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,`password`  varchar(80) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,`comment`  varchar(250) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,PRIMARY KEY (`userId`),UNIQUE INDEX `UQ_User_userName` (`userName`) USING BTREE)
复制代码

2.2. 创建实体类

复制代码
package com.mybatis.config;public class User {    private int userId;    private String userName;    private String password;    private String comment;
    // get  set 方法    public int getUserId() {        return userId;    }    public void setUserId(int userId) {        this.userId = userId;    }    public String getUserName() {        return userName;    }    public void setUserName(String userName) {        this.userName = userName;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }    public String getComment() {        return comment;    }    public void setComment(String comment) {        this.comment = comment;    }}
复制代码

3. 定义数据访问接口

复制代码
package com.mybatis.config;import java.util.List;public interface UserDao {
    // 对数据的访问主要为 增删改查        public int insert(User user);        public int update(User user);        public int delete(String userName);        public List<User> selectAll();        public int countAll();        public User findByUserName(String userName);}
复制代码

4.创建MyBatis映射文件(UserDaoMapper.xml)--数据访问接口映射文件,在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.mybatis.config.UserDao">    <select id="countAll" resultType="int">        select count(*) c from user;    </select>        <select id="selectAll" resultType="com.mybatis.config.User">        select * from user order by userName asc    </select>        <insert id="insert" parameterType="com.mybatis.config.User">        insert into user(userName,password,comment) values(#{userName},#{password},#{comment})    </insert>        <update id="update" parameterType="com.mybatis.config.User">        update user set userName=#{userName},password=#{password},comment=#{comment} where userName=#{userName}    </update>        <delete id="delete" parameterType="int">        delete from user where userName=#{userName}    </delete>        <select id="findByUserName" parameterType="String" resultType="com.mybatis.config.User">        select * from user where userName=#{userName}    </select></mapper>
复制代码

5. 创建mybatis配置文件--- 配置文件1,写入数据访问映射文件的路径 ,userMapperDao.xml 文件

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>
<mappers>
<mapper resource="com/mybatis/UserDaoMapper.xml"/>
</mappers>
</configuration>


6  编写服务层接口(UserService.java)
package com.mybatis;

public interface UserService {
public int countAll();
    public List<User> listAll();
}

编写服务层实现代码(UserServiceImpl.java)

package com.mybatis;
public class UserServiceImpl implements UserService {
private UserDao userDao;

public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}

public int countAll() {
return this.userDao.countAll();
}
   public list<User> listAll()
   {
        return this.userDao.selectAll();
   }
}

8 编写spring配置文件(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"
xsi:schemaLocation
="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/hlp?useUnicode=true&amp;characterEncoding=UTF-8&amp;zeroDateTimeBehavior=convertToNull"></property>
<property name="username" value="root"></property>
<property name="password" value="1234"></property>
<property name="maxActive" value="100"></property>
<property name="maxIdle" value="30"></property>
<property name="maxWait" value="500"></property>
<property name="defaultAutoCommit" value="true"></property>
</bean>

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:MyBatis-Configuration.xml"></property>
<property name="dataSource" ref="dataSource" />
</bean>

<bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.mybatis.UserDao"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>


<bean id="userService" class="com.mybatis.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>

</beans>

9. 编写测试代码

复制代码
package com.mybatis;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class UserServiceTest {

@Test
public void userServiceTest(){
ApplicationContext context
= new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService
= (UserService)context.getBean("userService");
System.out.println(userService.countAll());
}
}