首页 > 代码库 > Hello mybatis

Hello mybatis

idea玩mybatis,终于搞出个hello mybatis。记录下过程,备忘。

1、person表

CREATE TABLE `person` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) CHARACTER SET gb2312 NOT NULL,
  `password` varchar(20) CHARACTER SET latin1 NOT NULL,
  `sex` varchar(2) CHARACTER SET gb2312 DEFAULT NULL,
  `email` varchar(30) CHARACTER SET latin1 DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;

2、数据模型(bean)Person.java

package model;

/**
 * Created by DANNY on 2016/12/30.
 */
public class Person {
    private Integer id;
    private String name;
    private String passWord;
    private String sex;
    private String email;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

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

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

3、Person的mapper,xml配置文件

<?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="model.PersonMapper">
    <select id="queryPersonById" parameterType="int" resultType="Person"
            useCache="false">
        <![CDATA[
        select * from person where id = #{id}
        ]]>
    </select>
</mapper>

4、mybatis-config.xml配置文件

alias: 别名,第3步的resultType=“Person”,就是通过这里映射

<?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>
        <typeAlias type="model.Person" alias="Person" />
    </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://127.0.0.1:3306/test" />
                <property name="username" value="root" />
                <property name="password" value="test" />
            </dataSource>
        </environment>
    </environments>

    <!-- 配置mappers -->
    <mappers>
        <mapper resource="model/PersonMapper.xml" />
    </mappers>

</configuration>

5、测试类PersonTest.java

selectOne第一个参数,为第3步中mapper的namespace.id

import model.Person;
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;

/**
 * Created by DANNY on 2016/12/30.
 */
public class PersonTest {
    private static SqlSessionFactory sqlSessionFactory;
    private static Reader reader;

    static {
        try {
            reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new  SqlSessionFactoryBuilder().build(reader);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static SqlSessionFactory getSessionFactory(){
        return sqlSessionFactory;
    }

    public static void main(String[] args){
        SqlSession session = sqlSessionFactory.openSession();
        try {
            Person person = (Person)session.selectOne("model.PersonMapper.queryPersonById",1);
            System.out.println(person.getEmail());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            session.close();
        }
    }
}

运行测试类的main方法,可从数据库查询出id=1的记录

danny.yao@13.com

Process finished with exit code 0

6、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>danny.yao.mybatisLearning</groupId>
    <artifactId>mybatisLearning</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
    </dependencies>
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
</project>

 

Hello mybatis