mybatis框架学习实验一

mybatis框架学习实验一_第1张图片

建立项目后,需要在mysql数据库中创建一个名为mybatis的数据库,并建立user表

mybatis框架学习实验一_第2张图片

 

1.创建配置文件 mybatis.cfg.xml

其中<typeAliases>以及<mappers>为后面新增的

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>
    
    <package name="com.zoey.mybatis.model" />
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://localhost:3306/mybatis" />
                <property name="username" value="root" />
                <property name="password" value="" />
            dataSource>
        environment>        
    environments> 
    
    <mappers>
        
        <package name="com/zoey/mybatis/mapper" />
    mappers>

configuration>

2.创建实体类

package com.zoey.mybatis.model;

public class User {
    private Integer id;
    private String username;
    private String password;
    private String sex;
    private String address;
    
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    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 getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    
    

}

3.创建方法接口和定义映射文件

新建方法接口 UserMapper.java ,提供简单的增删改查数据操作。

UserMapper 接口的代码如下:

package com.zoey.mybatis.mapper;

import java.util.List;

import com.zoey.mybatis.model.User;

public interface UserMapper {
    public int insertUser(User user) throws Exception;
    
    public int updateUser(User user) throws Exception;
    
    public int deleteUser(Integer id) throws Exception;
    
    public User selectUserById(Integer id) throws Exception;
    
    public List selectAllUser() throws Exception;

}

定义映射文件UserMapper.xml

xml version="1.0" encoding="UTF-8"?>
DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zoey.mybatis.mapper.UserMapper">
    
    <resultMap id="userMap" type="User">
        <id property="id" column="id" javaType="int">id>
        <result property="username" column="username" javaType="String">result>
        <result property="password" column="password" javaType="String">result>
        <result property="sex" column="sex" javaType="String">result>
        <result property="address" column="address" javaType="String">result>
    resultMap>

    
    
    
    
    <insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
        insert into user (username,password,sex,address) values
        (#{username},#{password},#{sex},#{address})
    insert>

    <update id="updateUser"  parameterType="User">
        update user set
        address=#{address} where
        id=#{id}
    update>

    <delete id="deleteUser" parameterType="int">
        delete from user where
        id=#{id}
    delete>

    

    
    <select id="selectUserById" parameterType="int" resultType="User">
        select * from user where id=#{id}
    select>

    <select id="selectAllUser" resultMap="userMap">
        select * from user
    select>

mapper>

在 mybatis.cfg.xml 中加载它,在 mybatis.cfg.xml 中添加代码:

    <mappers>
        
        <package name="com/zoey/mybatis/mapper" />
    mappers>

 

同时为Java Bean 起别名,添加如下代码:

<typeAliases>
    
    <package name="com.zoey.mybatis.model" />
typeAliases>

4.创建测试类

package com.zoey.mybatis.test;

import java.io.IOException;
import java.io.InputStream;
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 com.zoey.mybatis.mapper.UserMapper;
import com.zoey.mybatis.model.User;

public class UserTest {
    private static SqlSessionFactory sqlSessionFactory;

    public static void main(String[] args) {
        String resource = "mybatis.cfg.xml";
        
        //得到配置文件流
        InputStream inputStream = null;
        try{
            inputStream = Resources.getResourceAsStream(resource);
        }catch(IOException ie){
            ie.printStackTrace();
        }
        
        // 创建会话工厂,传入 MyBatis 的配置文件信息
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

         insertUser();
        // updateUser();
        // deleteUser();
        // selectUserById();
        //selectAllUser();

    }

    // 新增用戶
    private static void insertUser() {
        // 通过工厂得到 SqlSession
        SqlSession session = sqlSessionFactory.openSession();

        UserMapper mapper = session.getMapper(UserMapper.class);
        User user = new User();
        user.setUsername("Tom");
        user.setPassword("123456");
        user.setSex("male");
        user.setAddress("chengdu");
        try {
            mapper.insertUser(user);

            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
            session.rollback();
        }

        // 释放资源
        session.close();
    }

    // 更新用戶
    private static void updateUser() {

        SqlSession session = sqlSessionFactory.openSession();

        UserMapper mapper = session.getMapper(UserMapper.class);
        User user = null;
        try {
            user = mapper.selectUserById(1);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        user.setAddress("chongqing");
        try {
            mapper.updateUser(user);
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
            session.rollback();
        }

        session.close();
    }

    // 删除用戶
    private static void deleteUser() {

        SqlSession session = sqlSessionFactory.openSession();

        UserMapper mapper = session.getMapper(UserMapper.class);
        try {
            mapper.deleteUser(3);
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
            session.rollback();
        }

        session.close();
    }

    // 根据id查询用户信息
    private static void selectUserById() {

        SqlSession session = sqlSessionFactory.openSession();

        UserMapper mapper = session.getMapper(UserMapper.class);
        try {
            User user = mapper.selectUserById(1);
            session.commit();
            System.out.println(user.getId() + " " + user.getUsername() + " "
                    + user.getPassword() + " " + user.getSex() + " "
                    + user.getAddress());
        } catch (Exception e) {
            e.printStackTrace();
            session.rollback();
        }

        session.close();
    }

    // 查询所有的用户信息
    private static void selectAllUser() {

        SqlSession session = sqlSessionFactory.openSession();

        UserMapper mapper = session.getMapper(UserMapper.class);
        try {
            List userList = mapper.selectAllUser();
            session.commit();
            for (User user : userList) {
                System.out.println(user.getId() + " " + user.getUsername() + " "
                        + user.getPassword() + " " + user.getSex() + " "
                        + user.getAddress());
            }
        } catch (Exception e) {
            e.printStackTrace();
            session.rollback();
        }

        session.close();
    }
}

 

转载于:https://www.cnblogs.com/zoeyqq/p/6934096.html

你可能感兴趣的:(mybatis框架学习实验一)