三大框架 SSM 之 Mybatis基础练习

官网: https://github.com/mybatis

中文网:http://www.mybatis.org/mybatis-3/zh/index.html

1.项目文件构架:

三大框架 SSM 之 Mybatis基础练习_第1张图片

2.导包:

1. mybatis包,在官网上可以下载 2. jdbc 包

这里写图片描述

3. model类:

@JAVA
package com.zhiyou100.model;

public class User {

    private Long id;
    private String username;
    private String password;
    private String email;


    public User() {
        super();
    }

    public User(Long id, String username, String password, String email) {
        super();
        this.id = id;
        this.username = username;
        this.password = password;
        this.email = email;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email + "]";
    }



    public Long getId() {
        return id;
    }

    public void setId(Long 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 getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

}

4. mybatis-config.xml 配置文件

这个部分我们在官网上可以直接拷贝, 只需要改变 相应的地方,与我们自己的数据库匹配起来就可以了



<configuration>

    <settings>
          
          <setting name="mapUnderscoreToCamelCase" value="true"/>
    settings>

    <typeAliases>
        
        <typeAlias type="com.zhiyou100.model.User" alias="_User"/>
    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/zyonlineforum" />
                <property name="username" value="root" />
                <property name="password" value="123456" />
            dataSource>
        environment>
    environments>
    <mappers>

        
        <mapper resource="UserMapper.xml" />

        
        <mapper class="com.zhiyou100.dao.CategoryDao"/>

    mappers>
configuration>

5.写DBUtil 工具类,单例模式

使用这个部分可以获取到 session
@java
package com.zhiyou100.util;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public enum DBUtil {

    INSTANCE;

    private SqlSessionFactory sessionFactory;

    private DBUtil() {

        String resource = "mybatis-config.xml";

        try(Reader reader = Resources.getResourceAsReader(resource);){

            sessionFactory = new SqlSessionFactoryBuilder().build(reader);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public SqlSessionFactory getSessionFactory() {
        return sessionFactory;
    }   
}

6. 写出UserDao 要实现的增,删,改,查语句:

@java
package com.zhiyou100.dao;

import java.util.List;

import org.apache.ibatis.annotations.Select;

import com.zhiyou100.model.User;

public interface UserDao {

    @Select("insert into user(username, password, email) values (#{username}, #{password}, #{email})")
    void saveUser(User user);

    @Select("update user set password=#{password} where username=#{username}")
    void updateUser(User user);

    @Select("delete from user where username=#{username}")
    void removeUser(User user);

    @Select("select * from user where username=#{username}")
    User getUser(String name);

    @Select("select * from user")
    List<User> listUser();

    @Select("select * from user where username like #{username}")
    List<User> listUserByName(String key);

}

7. 至此 , 我们对数据库的操作就完成了 ,我们可以建议个JUtil 测试文件,来测试我们所写的方法是否正确

@Test
    public void testListUser() {

        try (SqlSession session = DBUtil.INSTANCE.getSessionFactory().openSession()) {

            // 使用一种叫做 动态代理 的技术,帮我们创建一个类实现 UserDao 接口
            // 然后返回这个类的对象供我们使用
            // 1. Mapper.xml 的 namespace 必须和接口全名保持一致
            // 2. SQL 语句的 id,parameterType,resultType 
            //    必须和接口中的方法名,参数类型,返回值类型保持一致
            UserDao dao = session.getMapper(UserDao.class);

            List list = dao.listUser();

            for (User user : list) {

                System.out.println(user);
            }
        }
    }

你可能感兴趣的:(mybatis)