mybatis Annotation简单运用

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

1.创建数据库表(User表)

CREATE TABLE `user` (
`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. 创建实体类


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;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

public interface UserDao {
    @Insert("insert into user(userName,password,comment) values(#{userName},#{password},#{comment})")
    public int insert(User user);
    
    @Update("update user set userName=#{userName},password=#{password},comment=#{comment} where userName=#{userName}")
    public int update(User user);
    
    @Delete("delete from user where userName=#{userName}")
    public int delete(String userName);
    
    @Select("select * from user order by userName asc")
    public List<User> selectAll();
    
    @Select("select count(*) c from user;")
    public int countAll();
    
    @Select("select * from user where userName=#{userName}")
    public User findByUserName(String userName);
}

4.编写mybatis配置文件


<?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>
    <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/hlp?useUnicode=true&amp;characterEncoding=UTF-8&amp;zeroDateTimeBehavior=convertToNull" />
                <property name="username" value="root" />
                <property name="password" value="1234" />
            </dataSource>
        </environment>
    </environments>
</configuration>

5.数据库访问辅助类


package com.mybatis.config;

import java.io.IOException;
import java.io.Reader;
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 DbHelper {
    private static DbHelper dbHelper=null;
    private static SqlSessionFactory sqlSessionFactory=null;
    private DbHelper(){
        String resource = "MyBatis-Configuration.xml";
        Reader reader;
        try {
            reader = Resources.getResourceAsReader(resource);
            sqlSessionFactory =new SqlSessionFactoryBuilder().build(reader);
            sqlSessionFactory.getConfiguration().addMapper(UserDao.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
    public static DbHelper getInstance(){
        if(dbHelper==null)
            dbHelper = new DbHelper();
        return dbHelper;
    }
}

6.编写测试代码

package com.mybatis.config;

import java.util.Iterator;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

public class UserDaoTest {
    @Test
    public void userDaoTest() throws Exception
    {
        SqlSession session = DbHelper.getInstance().getSqlSession();
        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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值