mac下使用MyBatis增删改查(mysql,Java)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mac下使用MyBatis增删改查(mysql,Java)相关的知识,希望对你有一定的参考价值。

1.安装mysql

下载地址为http://dev.mysql.com/downloads/mysql/,选择dmg类型的直接下载,跳转的页面要求注册或登录,可以直接点击页面最下面的

No thanks, just start my download.

下载,安装

安装结束会提示默认密码:

2016-01-26T03:15:17.366026Z 1 [Note] A temporary password is generated for [email protected]: o)pa_.adT2wZ

If you lose this password, please consult the section How to Reset the Root Password in the MySQL reference manual.

安装之后在系统偏好设置最下面可以看到mysql图标。

2.修改密码,创建表格

安装之后在mac的终端中输入mysql会提示找不到命令,因为系统默认会查找/usr/bin下的命令,如果这个命令不在这个目录下就找不到命令,mysql默认安装在/usr/local/mysql/bin/mysql,需要建立一个链路指向这里,在终端中执行命令?$sudo ln -s /usr/local/mysql/bin/mysql /usr/bin

设置之后通过mysql --version可以查看mysql版本号,注意version前面是两个横线

mysql -u root -p回车,再输入密码回车即可进入mysql

首先需要修改密码,否则无法进行进一步操作

设置方式是SET PASSWORD = PASSWORD(‘your new password‘);?关于修改密码问题可以参考这里

密码修改之后就可以执行sql语句,例如select version(),current_date;会返回下面的结果:

version()?current_date?
5.7.10? 2016-01-26?

show databases ?显示已经创建的数据库,通过create database mydb; 创建名为“mydb”的数据库,使用drop database mydb;删除名为“mydb”的数据库,使用use mydb 选择使用“mydb”数据库,选中一个数据库之后可以创建表格。

?

mysql中创建表格时通过character set = utf8;使表格支持中文。

?

create table user ( id int auto_increment, userName varchar(50), userAge int,userAddress varchar(200), primary key (id) ) character set = utf8; 

?

3.使用MyBatis对mysql进行增删改查

创建maven项目,这个项目使用mybatis对mysql中user表进行增删改查操作,User是和表格对应的JavaBean.

package mybatis.demo;

/**
 * Created by zhangmeng27 on 16/1/27.
 */
public class User {

    public int id;
    public String userName;
    public int userAge;
    public String userAddress;

    public User (){
        super();
    }

    public User(int id, String userName, int userAge, String userAddress) {
        this.id = id;
        this.userName = userName;
        this.userAge = userAge;
        this.userAddress = userAddress;
    }

    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 int getUserAge() {
        return userAge;
    }

    public void setUserAge(int userAge) {
        this.userAge = userAge;
    }

    public String getUserAddress() {
        return userAddress;
    }

    public void setUserAddress(String userAddress) {
        this.userAddress = userAddress;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ",\tuserName=‘" + userName + ‘\‘‘ +
                ",\tuserAge=" + userAge +
                ",\tuserAddress=‘" + userAddress + ‘\‘‘ +
                ‘}‘;
    }
}

项目目录结构如下图,pom.xml添加mysql和mybatis的依赖,并添加拷贝xml配置文件到target目录下的相关配置

技术分享

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>java.test</groupId>
    <artifactId>mybatis_demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.1.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

</project>

使用mybatis主要要配置两类xml文件,一个是用于连接数据库和xml映射文件的,这里就是db_conf.xml,注意要修改连接数据库的password。

<?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">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/test?useSSL=true" />
                <property name="username" value="root" />
                <property name="password" value=“*****" />
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="mybatis/demo/UserMapper.xml" />
    </mappers>

</configuration>



这个文件的environment部门配置了连接数据库所需的信息,mappers部分配置了一个xml映射文件,即mybatis.demo包下面的UserMapper.xml,这个配置文件包含了对数据库增删改查相关的sql映射语句,其中mapper标签中的namespace需要写这个xml文件所在包名和文件名,但不包括后缀。代码中会使用每个增删改查子标签的id来使用对应的sql语句。

<?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="mybatis.demo.UserMapper">

    <insert id="insertUser" parameterType="mybatis.demo.User">
        insert into user(id,userName,userAge,userAddress)
         values(#{id},#{userName},#{userAge},#{userAddress})
    </insert>

    <insert id="insertUserWithoutId" parameterType="mybatis.demo.User" useGeneratedKeys="true" keyProperty="id">
        insert into user(userName,userAge,userAddress) values(#{userName},#{userAge},#{userAddress})
    </insert>

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

    <select id="getUser" parameterType="int" resultType="mybatis.demo.User">
                select userName as userName from user where id = #{id}
    </select>

    <select id="getCount" resultType="_int">
        select count(*) from user
    </select>

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

    <update id="setUser" parameterType="mybatis.demo.User">
        update user set userName=#{userName} where id=#{id}
    </update>

</mapper>



和UserMapper.xml对应的文件是UserMapper.java,这是一个接口类,里面定义了若干方法,每个方法的方法名和UserMapper.xml中每条增删改查子标签的id相同。

package mybatis.demo;


/**
 * Created by zhangmeng27 on 16/1/27.
 */
public interface UserMapper {

    public User selectUserById(int id);
    public void insertUser(User user);
    public void insertUserWithoutId(User user);
    public int  getCount();
    public void setUser(User user);

}



为了使用mybatis,写了一个工厂类ConnectionFactory.java,可以方便的得到sqlSession,这个文件需要读取db_conf.xml,运行的时候ConnectionFactory是在target目录下,所以需要将db_conf.xml拷贝到target目录下,拷贝工作是通过pom.xml中build部分的代码自动完成的。

package mybatis.demo;

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

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

/**
 * Created by zhangmeng27 on 16/1/27.
 */
public class ConnectionFactory {

    private static SqlSessionFactory factory;

    static {

        try {
            Reader reader = Resources.getResourceAsReader("db_conf.xml");
            factory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static SqlSessionFactory getSqlSessionFactory(){

        return factory;

    }

}



UserManager.java写了具体的数据库增删改查静态方法,类中的方法名可以随便取,但是为了和映射文件对应,这个类中的方法名和映射文件中的id及方法名一致,但是UserManager.java和UserMapper.java之间没有实现关系。

package mybatis.demo;

import org.apache.ibatis.session.SqlSession;

/**
 * Created by zhangmeng27 on 16/1/27.
 */
public class UserManager {

    public static User selectUserById(int id){
        SqlSession sqlSession = ConnectionFactory.getSqlSessionFactory().openSession();
        try{
            UserMapper user = sqlSession.getMapper(UserMapper.class);

            return user.selectUserById(id);
        }
        finally {
            sqlSession.close();
        }
    }

    public static void insertUserWithoutId(User u){
        SqlSession sqlSession = ConnectionFactory.getSqlSessionFactory().openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        userMapper.insertUserWithoutId(u);
        sqlSession.commit();
        sqlSession.close();

    }

    public static void insertUser(User u){

        SqlSession sqlSession = ConnectionFactory.getSqlSessionFactory().openSession();

        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        userMapper.insertUser(u);

        sqlSession.commit();//这里必须提交,否则运行提示已经插入,但是数据库中没有记录。

        sqlSession.close();

    }

    public static int getCount(){
        SqlSession sqlSession = ConnectionFactory.getSqlSessionFactory().openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        int n = userMapper.getCount();
        sqlSession.commit();
        sqlSession.close();
        return n;
    }

    public static void setUser(User user){
        SqlSession sqlSession = ConnectionFactory.getSqlSessionFactory().openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        userMapper.setUser(user);
        sqlSession.commit();
        sqlSession.close();
    }
}



RunTest.java调用UserManager.java中的方法完成数据库的增删改查操作。

package mybatis.demo;


/**
 * Created by zhangmeng27 on 16/1/27.
 */
public class RunTest {

    public static void main(String[] args) {
        crud();
    }

    public static void crud() {

        int id = 0;
        //插入数据
        User u = UserManager.selectUserById(id);
        if (u == null) {
            u = new User(id, "winter", 30, "jinan");
            UserManager.insertUser(u);
            System.out.println("新增用户为:" + u);
        } else {
            System.out.println("id="+id+"的用户已经存在 " + u);
        }


        int nameIndex = UserManager.getCount()+1;
        u = new User(nameIndex,"mybatis"+nameIndex,28+nameIndex,"usa NO."+nameIndex);
        UserManager.insertUserWithoutId(u);

        u.setUserName("mybatis" + nameIndex + "_fixed");
        UserManager.setUser(u);

        //查询数据
        User user = null;
        int index = 0;
        while(true){
            user = UserManager.selectUserById(++index);
            if (user != null) {
                System.out.println(user.toString());
            } else {
                System.out.println("id = "+index+" 的查询结果为 " + null);
                break;
            }
        }
    }
}

?

运行RunTest即可看到数据库增删改查对应的输出,没运行一次会递增向数据库中增加一条记录。如果读取出错,即数据库中有多条记录,但是最后只能循环读取少数记录,需要坚持是否有记录id不连续的情况,如果记录不连续可以修改crud()方法中id的值插入对应id的值。

?


以上是关于mac下使用MyBatis增删改查(mysql,Java)的主要内容,如果未能解决你的问题,请参考以下文章

mybatis+oracle:批量操作(增删改查)

如何使用mybatis对mysql数据库进行操作,batis的增删改查

Mybatis实现简单的数据库增删改查操作

Mybatis实现简单的数据库增删改查操作

MyBatis框架入门小案例(关于用mybatis框架对数据库的增删改查)

SpringBoot + MyBatis 实现对员工的增删改查