美文网首页
创建最简单的mybatis应用2-基于接口的实现

创建最简单的mybatis应用2-基于接口的实现

作者: ssttIsme | 来源:发表于2019-03-14 19:56 被阅读0次

使用sqlyou在mysql的自带test库创建一张表,sql脚本如下

USE test;
CREATE TABLE product(
id INT(11) NOT NULL AUTO_INCREMENT,
product_name VARCHAR(200)NOT NULL,
store INT(11),
created DATE DEFAULT NULL,
updated DATE DEFAULT NULL,
PRIMARY KEY(id)
)DEFAULT CHARSET=utf8;

INSERT INTO product VALUES
(NULL,'apple',50,NOW(),NOW()),
(NULL,'pear',60,NOW(),NOW());
创建后表如图

创建maven项目





抽出数据库的配置
项目结构

pom.xml

<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.mybatis</groupId>
    <artifactId>mybatis-basic2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.8</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.40</version>
        </dependency>
    </dependencies>
</project>

dbconfig.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql:///test
username=root
password=g

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">
<!--dtd约束属于xml文档约束,通过dtd定义文档中的元素都有哪些,这些元素的嵌套关系是怎样的,这些元素的先后顺序是怎样的 -->
<configuration>
    <!-- 关联properties文件 -->
    <properties resource="dbconfig.properties" />
    <settings>
        <!--启用缓存(有的默认就是开启的) -->
        <setting name="cacheEnabled" value="true" />
        <!--开启驼峰规则  -->
        <setting name="mapUnderscoreToCamelCase" value="true" />
    </settings>
    <typeAliases>
        <!--设置类的别名 默认为指定包中的类定义一个别名,这个别名为类名的第一个单词的首字母小写 -->
        <package name="com.project.pojo"  />
    </typeAliases>
    <!--配置开发环境 -->
    <environments default="development">
        <environment id="development">
            <!--事务管理环境 -->
            <transactionManager type="JDBC" />
            <!--配置数据源 -->
            <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="mapper/ProductMapper.xml" />
    </mappers>
</configuration>

ProductMapper.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">
<!--mybatis中的映射文件 -->
<!--定义一个sql查询,sql查询必须有一个id,其中resultType表示查询结果会封装到对应的map类型中,一行记录对应一个map -->
<mapper namespace="com.project.dao.ProductDao">
    <select id="findAll" resultType="product">
        select * from product
    </select>
</mapper>

Product.java

package com.project.pojo;

import java.util.Date;

public class Product {
    private Integer id;
    private String productName;
    private Integer store;
    private Date created;
    private Date updated;

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getProductName() {
        return productName;
    }
    public void setProductName(String productName) {
        this.productName = productName;
    }
    public Integer getStore() {
        return store;
    }
    public void setStore(Integer store) {
        this.store = store;
    }
    public Date getCreated() {
        return created;
    }
    public void setCreated(Date created) {
        this.created = created;
    }
    public Date getUpdated() {
        return updated;
    }
    public void setUpdated(Date updated) {
        this.updated = updated;
    }
    @Override
    public String toString() {
        return "Product [id=" + id + ", productName=" + productName + ", store=" + store + ", created=" + created
                + ", updated=" + updated + "]";
    }

}

ProductDao.java

package com.project.dao;

import java.util.List;

import com.project.pojo.Product;

public interface ProductDao {
    /**
     * 接口中方法名要与mapper文件中sqlid相同
     * 返回值类型要与sqlid对象的返回值类型匹配
     * @return
     */
    List<Product>findAll();
}

TestProduct.java

package com.project.test;

import java.io.IOException;
import java.util.List;

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 com.project.dao.ProductDao;
import com.project.pojo.Product;

public class TestProduct {
    private  static SqlSessionFactory factory;
    public static void init() throws IOException{
        factory=new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
    }
    public static void findAll()throws IOException{
        init();
        SqlSession session=factory.openSession();
        //通过session获取一个dao对象
        ProductDao dao = session.getMapper(ProductDao.class);
        List<Product> list = dao.findAll();
        System.out.println(list);
        //释放资源
        session.close();
    }
    public static void main(String[] args) {
        
        try {
            findAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        
        
    }
}

运行结果

[Product [id=1, productName=apple, store=50, created=Mon Mar 11 00:00:00 CST 2019, updated=Mon Mar 11 00:00:00 CST 2019], Product [id=2, productName=pear, store=60, created=Mon Mar 11 00:00:00 CST 2019, updated=Mon Mar 11 00:00:00 CST 2019]]

相关文章

网友评论

      本文标题:创建最简单的mybatis应用2-基于接口的实现

      本文链接:https://www.haomeiwen.com/subject/iyocmqtx.html