Home >Database >Mysql Tutorial >mybatis简单应用(基于配置文件)_MySQL

mybatis简单应用(基于配置文件)_MySQL

WBOY
WBOYOriginal
2016-06-01 13:11:591632browse

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

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;    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);}</user>

4.创建MyBatis映射文件(UserDaoMapper.xml)

<?xml version="1.0" encoding="UTF-8" ?>   <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配置文件
<?xml version="1.0" encoding="UTF-8" ?><configuration>    <environments default="development">        <environment id="development">            <transactionmanager type="JDBC"></transactionmanager>            <datasource type="POOLED">                <property name="driver" value="com.mysql.jdbc.Driver"></property>                <property name="url" value="jdbc:mysql://localhost:3306/hlp?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull"></property>                <property name="username" value="root"></property>                <property name="password" value="1234"></property>            </datasource>        </environment>    </environments>    <mappers>        <mapper resource="com/mybatis/config/UserDaoMapper.xml"></mapper>    </mappers></configuration>

6. 编写测试代码

package com.mybatis.config;import java.io.Reader;import java.util.Iterator;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;import org.junit.Test;public class UserDaoTest {    @Test    public void userDaoTest() throws Exception    {        String resource = "MyBatis-Configuration.xml";        Reader reader = Resources.getResourceAsReader(resource);        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();        SqlSessionFactory factory = builder.build(reader);                SqlSession session = factory.openSession();        UserDao userDao = session.getMapper(UserDao.class);                User user = new User();        user.setUserName("hongye");        user.setPassword("123456");        user.setComment("备注");                userDao.insert(user);        System.out.println("记录条数:"+userDao.countAll());                List<user> users = userDao.selectAll();        Iterator<user> iter = users.iterator();        while(iter.hasNext()){            User u = iter.next();            System.out.println("用户名:"+u.getUserName()+"密码:"+u.getPassword());        }                user.setComment("comment");        userDao.update(user);        User u = userDao.findByUserName("hongye");        System.out.println(u.getComment());                userDao.delete("hongye");        System.out.println("记录条数:"+userDao.countAll());                session.commit();        session.close();    }}</user></user>


作者:红枫落叶 
出处:http://www.cnblogs.com/wushiqi54719880/ 
关于作者:专注于Java企业运用、海量数据处理、hadoop、数字图像处理等。
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,如有问题,可以通过wushiqi54719880@126.com  联系我,非常感谢。
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn