第一节:mybatis入门

1、新建数据表


本次测试使用mysql数据,数据库名称为mybatis,新建一张表person,建表语句如下:

CREATE TABLE `person` (
`id` INT ( 11 ) PRIMARY KEY auto_increment,
`first_name` VARCHAR ( 255 ),
`last_name` VARCHAR ( 255 ),
`age` INT ( 11 ),
`email` VARCHAR ( 255 ),
`address` VARCHAR ( 255 ) 
);

插入测试数据如下:

insert into person(first_name,last_name,age,email,address) VALUES('Schmitt', 'Carine',25,null,'beijing');
insert into person(first_name,last_name,age,email,address) VALUES('King', 'Jean',36,'Jean@163.com','beijing');
insert into person(first_name,last_name,age,email,address) VALUES('Ferguson', 'Schmitt',23,'88888@qq.com','shanghai');
insert into person(first_name,last_name,age,email,address) VALUES('Piestrzeniewicz', 'Nelson',55,null,'nanjing');
insert into person(first_name,last_name,age,email,address) VALUES('Jytte', 'Jean',22,'55555@qq.com','shenzhen');
insert into person(first_name,last_name,age,email,address) VALUES('Victorino', 'Diego',19,'Diego@163.com','shanghai');
insert into person(first_name,last_name,age,email,address) VALUES('Julie', 'Schmitt',56,null,'nanjing');
insert into person(first_name,last_name,age,email,address) VALUES('Gao', 'Diego',45,'66666@qq.com','beijing');
insert into person(first_name,last_name,age,email,address) VALUES('Piestrzeniewicz', 'Schmitt',36,'44444@qq.com','beijing');
insert into person(first_name,last_name,age,email,address) VALUES('Frdrique', 'Juri',25,'99999@qq.com','beijing');

结果如下:

数据表格

2、mybatis入门


1、新建maven工程

本次演示使用IntelliJ IDEA社区版,新建一个maven工程,最终结果如下:

mybatis工程结构

2、添加依赖,主要是mybatis和mysql

<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.6</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
</dependencies>

3、编写数据库表person对应的实体。

package com.yefengyu.mybatis.entity;

public class Person
{
    private Integer id;

    private String firstName;

    private String lastName;

    private Integer age;

    private String email;

    private String address;

    public Integer getId()
    {
        return id;
    }

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

    public String getFirstName()
    {
        return firstName;
    }

    public void setFirstName(String firstName)
    {
        this.firstName = firstName;
    }

    public String getLastName()
    {
        return lastName;
    }

    public void setLastName(String lastName)
    {
        this.lastName = lastName;
    }

    public Integer getAge()
    {
        return age;
    }

    public void setAge(Integer age)
    {
        this.age = age;
    }

    public String getEmail()
    {
        return email;
    }

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

    public String getAddress()
    {
        return address;
    }

    public void setAddress(String address)
    {
        this.address = address;
    }

    @Override
    public String toString()
    {
        return "Person{" +
               "id=" + id +
               ", firstName='" + firstName + '\'' +
               ", lastName='" + lastName + '\'' +
               ", age=" + age +
               ", email='" + email + '\'' +
               ", address='" + address + '\'' +
               '}';
    }
}

4、编写mapper接口

package com.yefengyu.mybatis.mapper;

import com.yefengyu.mybatis.entity.Person;


public interface PersonMapper
{
    Person getPerson(Integer id);
}

5、编写mapper映射文件

在resources下面新建一个mapper文件夹,再在里面新建一个PersonMapper.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="com.yefengyu.mybatis.mapper.PersonMapper">
    <select id="getPerson" resultType="com.yefengyu.mybatis.entity.Person">
        select * from person where id = #{id}
    </select>
</mapper>

6、新建一个mybatis全局配置文件,详细信息见官网

在resources下面新建mybatis-config.xml文件,内容如下:

<?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://127.0.0.1:3306/mybatis?characterEncoding=utf8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="mapper/PersonMapper.xml"/>
  </mappers>
</configuration>

7、测试

package com.yefengyu.mybatis;

import com.yefengyu.mybatis.mapper.PersonMapper;
import com.yefengyu.mybatis.entity.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.IOException;
import java.io.InputStream;


public class Main
{
    public static void main(String[] args)
        throws IOException
    {
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
        Person person = mapper.getPerson(1);
        System.out.println(person);
        sqlSession.close();
    }
}

8、结果

Person{id=1, firstName='null', lastName='null', age=25, email='null', address='beijing'}

分析:这条查询的结果和数据库相比,firstName和lastName字段查询有问题,没有查询到结果,这个主要原因是数据库字段命名是使用下划线,而java实体使用驼峰法命名,导致mybatis无法自动匹配,解决方法有很多,此处使用最原始的一种:给查询语句中的字段添加别名的方式

<?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="com.yefengyu.mybatis.mapper.PersonMapper">
    <select id="getPerson" resultType="com.yefengyu.mybatis.entity.Person">
        select * from person where id = #{id}
    </select>
</mapper>

中的查询语句由

select * from person where id = #{id}

改为下面这句

select id, first_name firstName, last_name lastName, age, email, address  from person where id = #{id}

这样就可以查询到我们需要看到的效果,是不是很神奇?

Person{id=1, firstName='Schmitt', lastName='Carine', age=25, email='null', address='beijing'}
posted @ 2019-06-04 22:40  代码梦工厂  阅读(514)  评论(0编辑  收藏  举报