IDEA中入门搭建Mybatis,并对数据库做增删改查

1.新建项目,如下图 :

è¿éåå¾çæè¿°

è¿éåå¾çæè¿°

2、导入mybatis所需要jar包,并加入依赖 add as library 
mybatis需要jar包:mybatis-3.4.6.jar 
mysql驱动jar包:mysql-connector-java-5.1.42.-bin.jar 
日志记录jar包:log4j-1.2.14.jar 
junit测试包:junit-4.12.jar和hamcrest-core-1.3.jar 
所需jar包下载地址,包含整个项目代码 

6、src下创建文件jdbc.properties 
加上的useSSL=false原因是: 
https://blog.csdn.net/u010429286/article/details/77750177

jdbc.properties代码如下:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=UTF-8&useSSL=false
jdbc.username=root
jdbc.password=root


7、src下添加mybatis配置文件mybatis.cfg.xml, 
创建mybatis.cfg.xml文件具体步骤看连接: 
https://blog.csdn.net/nba_linshuhao/article/details/82735770

mybatis.cfg.xml代码如下:(不是最终的,因为下面还需要添加内容)





    
    

    
    
        
            
            

            
            
            
            
            
                
                
                
                
            
        
    

8、log4j.properties代码如下:

### 设置Logger输出级别和输出目的地 ###
log4j.rootLogger=debug,stdout,logfile

### 把日志信息输出到控制台 ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout

### 把日志信息输出到文件:jbit.log ###
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=jbit.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n

###显示SQL语句部分
log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

9、创建对应的实体对象文件: User.java 

package com.cy.mybatis.beans;
import java.io.Serializable;
public class User implements Serializable {
    public  User(){}; 
    public  User(String username,String password,Double account){
        this.username=username;
        this.password=password;
        this.account=account;
    }
    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 Double getAccount() {
        return account;
    }

    public void setAccount(Double account) {
        this.account = account;
    }

    private  Integer id;
    private  String username;
    private  String password;
    private Double account;


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

10.创建方法接口UserMapper.java和定义操作user表的sql映射文件UserMapper.xml

è¿éåå¾çæè¿°

package com.cy.mybatis.mapper;
import com.cy.mybatis.beans.User;
import java.util.List;

public interface UserMapper {
    /**
     * 新增用戶
     * @param user
     * @return
     * @throws Exception
     */
    public int insertUser(User user) throws Exception;
    /**
     * 修改用戶
     * @param user
     * @param id
     * @return
     * @throws Exception
     */
    public int updateUser (User user,int id) throws Exception;
    /**
     * 刪除用戶
     * @param id
     * @return
     * @throws Exception
     */
    public int deleteUser(int id) throws Exception;
    /**
     * 根据id查询用户信息
     * @param id
     * @return
     * @throws Exception
     */
    public User selectUserById(int id) throws Exception;
    /**
     * 查询所有的用户信息
     * @return
     * @throws Exception
     */
    public List selectAllUser() throws Exception;
}
package com.cy.mybatis.mapper;
import com.cy.mybatis.beans.User;
import java.util.List;

public interface UserMapper {
    /**
     * 新增用戶
     * @param user
     * @return
     * @throws Exception
     */
    public int insertUser(User user) throws Exception;
    /**
     * 修改用戶
     * @param user
     * @param id
     * @return
     * @throws Exception
     */
    public int updateUser (User user,int id) throws Exception;
    /**
     * 刪除用戶
     * @param id
     * @return
     * @throws Exception
     */
    public int deleteUser(int id) throws Exception;
    /**
     * 根据id查询用户信息
     * @param id
     * @return
     * @throws Exception
     */
    public User selectUserById(int id) throws Exception;
    /**
     * 查询所有的用户信息
     * @return
     * @throws Exception
     */
    public List selectAllUser() throws Exception;
}

11、这时需要在mybatis.cfg.xml里注册UserMapper.xml文件 





    
    

    
        
             
             
             
        


    
    
        
            
            

            
            
            
            
            
                
                
                
                
            
        
    

      
    
        
        
        
        
    


12、创建工具类文件DBTools.java 

è¿éåå¾çæè¿°

package com.cy.mybatis.tools;

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 java.io.Reader;

public class DBTools {
    public static SqlSessionFactory sessionFactory;

    static{
        try {
            //使用MyBatis提供的Resources类加载mybatis的配置文件
            Reader reader = Resources.getResourceAsReader("mybatis.cfg.xml");
            //构建sqlSession的工厂
            sessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    //创建能执行映射文件中sql的sqlSession
    public static SqlSession getSession(){
        return sessionFactory.openSession();
    }
}

13、编写测试文件UserServiceTest.java 

è¿éåå¾çæè¿°

package com.cy.mybatis.service;

import com.cy.mybatis.beans.User;
import com.cy.mybatis.mapper.UserMapper;
import com.cy.mybatis.tools.DBTools;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;

public class UserServiceTest {
    @Test
    //添加操作
    public void insertUser() throws Exception {
        SqlSession session = DBTools.getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        User user = new User("香蕉", "8888", 8888.8);
        try {
            mapper.insertUser(user);
            System.out.println(user.toString());
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
            session.rollback();
        }
    }

    @Test
    //删除操作
    public void deleteUser() throws Exception {
        SqlSession session=DBTools.getSession();
        UserMapper mapper=session.getMapper(UserMapper.class);
        try {
            mapper.deleteUser(1);
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
            session.rollback();
        }
    }

    @Test
    //选择操作
    public void selectUserById() throws Exception {
        SqlSession session=DBTools.getSession();
        UserMapper mapper=session.getMapper(UserMapper.class);
        try {
     //这里用到User类的无参构造方法创建对象,User user=new User();
            User user =mapper.selectUserById(2);
            System.out.println(user.toString());

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

    @Test
    public void selectAllUser() throws Exception {
        SqlSession session= DBTools.getSession();
        UserMapper mapper=session.getMapper(UserMapper.class);
        try {
            List user=mapper.selectAllUser();
            System.out.println(user.toString());
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
            session.rollback();
        }
    }

}

 

你可能感兴趣的:(作业)