mybatis實現增刪改查xml配置和後端Java編程完整教程

mybatis實現增刪改查xml配置和後端編程教程

SqlMapConfig.xmljava

<?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">
                <!-- 使用jdbc事務管理 -->
                <transactionManager type="JDBC"/>
                <!-- 數據庫鏈接池 -->
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="011220"/>
                </dataSource>
            </environment>
        </environments>
        <mappers>
            <mapper resource="sqlmap/user.xml"/>
        </mappers>
    </configuration>

user.xmlmysql

<?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="test">
        <!-- 根據用戶id查詢用戶信息 -->
        <select id="findUserById" parameterType="int" resultType="cn.nwtxxb.mybatis.po.User">
            select * from user where id = #{id}
        </select>
        <!-- 根據用戶名查詢用戶信息 -->
        <select id="findUserByUserName" parameterType="java.lang.String" resultType="cn.nwtxxb.mybatis.po.User">
            select * from user where username like '%${value}%'
        </select>
        <!-- 添加用戶 -->
        <insert id="insertUser" parameterType="cn.nwtxxb.mybatis.po.User">
            <!-- selectKey將主鍵返回 -->
            <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
                select LAST_INSERT_ID()
            </selectKey>
            insert into user (username,birthday,sex,address) values (#{username},#{birthday},#{sex},#{address})
        </insert>
        <!-- 刪除用戶 -->
        <delete id="deleteUserById" parameterType="int">
            delete from user where id=#{id}
        </delete>
    </mapper>

User.javasql

package cn.nwtxxb.mybatis.po;

    import java.util.Date;

    public class User {
        private int id;
        private String username;
        private String sex;
        private Date birthday;
        private String address;
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getUsername() {
            return username;
        }
        public void setUsername(String username) {
            this.username = username;
        }
        public String getSex() {
            return sex;
        }
        public void setSex(String sex) {
            this.sex = sex;
        }
        public Date getBirthday() {
            return birthday;
        }
        public void setBirthday(Date birthday) {
            this.birthday = birthday;
        }
        public String getAddress() {
            return address;
        }
        public void setAddress(String address) {
            this.address = address;
        }
        @Override
        public String toString() {
            return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address="
                    + address + "]";
        }

    }

測試類代碼:數據庫

package cn.nwtxxb.mybatis.test;
import java.io.InputStream;
import java.util.Date;
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.Before;
import org.junit.Test;  
import cn.nwtxxb.mybatis.po.User;   
public class Mybatis_first {
    //會話工廠
    private SqlSessionFactory sqlSessionFactory;
    @Before
    public void createSqlSessionFactory() throws Exception{
        //配置文件
        String resource = "SqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //使用SqlSessionFactoryBuilder從xml配置文件中建立SqlSessionFactory
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }
    //根據id查詢用戶信息
    @Test
    public void testFindUserById(){
        //數據庫會話實例
        SqlSession sqlSession = null;
        try {
            //建立數據庫會話實例sqlSession
            sqlSession = sqlSessionFactory.openSession();
            //查詢單個記錄,根據用戶id查詢用戶信息
            User user = sqlSession.selectOne("test.findUserById",10);
            //輸出用戶信息
            System.out.println(user);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if(sqlSession!=null){
                sqlSession.close();
            }
        }
    }
    //根據用戶名查詢用戶信息
    @Test
    public void testFindUserByUsername(){
        //數據庫會話實例
        SqlSession sqlSession = null;
        try {
            //建立數據庫會話實例sqlSession
            sqlSession = sqlSessionFactory.openSession();
            //根據用戶名中包含"張"的條件查詢用戶信息
            List<User> list = sqlSession.selectList("test.findUserByUserName","張");
            System.out.println(list.size());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if(sqlSession!=null){
                sqlSession.close();
            }
        }
    }
    //添加用戶信息
    @Test
    public void testInsert(){
        //數據庫會話實例
        SqlSession sqlSession = null;
        try {
            //建立數據庫會話實例sqlSession
            sqlSession = sqlSessionFactory.openSession();
            //添加用戶信息
            User user = new User();
            user.setUsername("張磊");
            user.setSex("1");
            user.setAddress("襄城");
            user.setBirthday(new Date());
            sqlSession.insert("test.insertUser",user);
            //提交事務
            sqlSession.commit();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if(sqlSession!=null){
                sqlSession.close();
            }
        }
    }
    //刪除用戶
    @Test
    public void testDelete(){
        //數據庫會話實例
        SqlSession sqlSession = null;
        try {
            //建立數據庫會話實例sqlSession
            sqlSession = sqlSessionFactory.openSession();
            sqlSession.delete("test.deleteUserById",26);
            sqlSession.commit();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if(sqlSession!=null){
                sqlSession.close();
            }
        }
    }
}

login4j.propertiesapache

# Global logging configuration
log4j.rootLogger=DEBUG,stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
相關文章
相關標籤/搜索