欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

mybatis简单的curd操作以及转账操作

程序员文章站 2022-04-05 08:43:46
...

mybatis简单的curd操作以及转账操作

使用mybatis框架进行简单的curd操作以及转账操作 数据库接口请参照下面的pojo类进行创建即可

代码如下

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.itheiama</groupId>
    <artifactId>mybatis03</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>
    </dependencies>

</project>

数据库信息 jdbcConfig.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybaties
username=root
password=123456

log4j基本配置(log4j.properties)

### 全局日志等级配置,输出位置配置###
log4j.rootLogger=debug,stdout 
### 输出信息到控制台 ###
# 配置日志信息输出目的地Appender
log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
log4j.appender.stdout.Target=System.out  
# 配置日志信息的格式布局(layout)
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

pojo实体类

package com.itheima.domain;

import java.io.Serializable;
import java.util.Date;
/**
* @Description 用户实体类
* @Params
* @Return
* @Author Xu Feng
* @Date 2019/9/15 12:04
**/

public class User implements Serializable {

    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;
    private Float money;

    public Float getMoney() {
        return money;
    }

    public void setMoney(Float money) {
        this.money = money;
    }

    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 Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    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;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                ", money=" + money +
                '}';
    }
}

接口类 (dao层)

package com.itheima.dao;

import com.itheima.domain.User;

import java.util.List;

/**
* @Description 用户持久层
* @Params
* @Return
* @Author Xu Feng
* @Date 2019/9/15 12:03
**/
public interface IUserDao {
    /**
    * @Description 查找所有
    * @Params
    * @Return
    * @Author Xu Feng
    * @Date 2019/9/15 12:03
    **/
    List<User> findAll();

    /**
    * @Description 根据姓名查找
    * @Params
    * @Return
    * @Author Xu Feng
    * @Date 2019/9/26 21:42
    **/
    List<User> findByName(String name);

    /**
    * @Description 获取用户的金钱
    * @Params
    * @Return
    * @Author Xu Feng
    * @Date 2019/9/26 23:24
    **/

    float getMoney(User user);

    /**
    * @Description 转账操作
    * @Params
    * @Return
    * @Author Xu Feng
    * @Date 2019/9/26 21:58
    **/
    void updateByName(User user);

}

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>
    <!-- 引用数据库配置文件 -->
    <properties resource="JDBCConfig.properties"></properties>
    <!-- 类起别名 -->
    <typeAliases>
        <package name="com.itheima.domain"/>
    </typeAliases>
    <!-- 数据库配置 -->
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <!-- 数据库配置 -->
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 映射配置 -->
    <mappers>
        <mapper resource="com/itheima/dao/UserDao.xml"></mapper>
    </mappers>
</configuration>

test测试类

package com.itheima.test;

import com.itheima.dao.IUserDao;
import com.itheima.domain.User;
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.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;

import java.util.List;

public class TestMybatis {

    private InputStream in;
    private SqlSessionFactory factory;
    private SqlSession sqlSession;
    private IUserDao userDao;

    @Before
    public void init() throws Exception{
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        factory = new SqlSessionFactoryBuilder().build(in);
        sqlSession = factory.openSession();
        userDao = sqlSession.getMapper(IUserDao.class);
    }

    @After
    public void destory() throws Exception{
        sqlSession.commit();
        in.close();
        sqlSession.close();
    }

    @Test
    public void testFindAll(){
        List<User> users = userDao.findAll();
        for (User user : users){
            System.out.println(user);
        }
    }

    @Test
    public void testFindByName(){
        User user = new User();
        user.setUsername("eee");
        List<User> users = userDao.findByName(user.getUsername());
        System.out.println(users.isEmpty()?null:users.get(0));
    }

    /**
    * @Description 获取用户的金钱
    * @Params
    * @Return
    * @Author Xu Feng
    * @Date 2019/9/26 23:21
    **/

    public float getMoney(String name){
        User user = new User();
        user.setUsername(name);
        return userDao.getMoney(user);
    }

    /**
    * @Description 实现转账操作
    * @Params
    * @Return
    * @Author Xu Feng
    * @Date 2019/9/26 23:22
    **/

    public void Tranform(String topeople,String inpeople, Float money){
        User inuser = new User();
        inuser.setUsername(topeople);
        inuser.setMoney(this.getMoney(topeople)-100f);
        userDao.updateByName(inuser);
        User touser = new User();
        touser.setUsername(inpeople);
        touser.setMoney(this.getMoney(inpeople)+100f);
        userDao.updateByName(touser);
    }

    @Test
    public void testTransform(){
        this.Tranform("eee","shown",100f);
    }


}