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

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

作者: ssttIsme | 来源:发表于2019-03-19 13:22 被阅读0次
项目结构

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>

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>

dbconfig.properties

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

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">
    <!-- 借助sql元素可以对重复编写的sql语句进行提取 -->
    <sql id="tableName"> product </sql>
    <sql id="fromTable">
        from
        <include refid="tableName" />
    </sql>

    <select id="findAll" resultType="product">
        select *
        <include refid="fromTable" />
    </select>
    <select id="findById" parameterType="int" resultType="product">
        select *
        <include refid="fromTable" />
        where id=#{id}
    </select>
    <select id="findByName" resultType="product">
        select *
        <include refid="fromTable" />
        where product_name like concat("%",#{productName},"%")
    </select>
    <select id="findProduct" resultType="product">
        select *
        <include refid="fromTable" />
        order by ${columnName} desc
    </select>
    <!-- useGeneratedKeys="true" 表示要使用自增长的id,获取到这个值以后要将这个值赋值给product对象的keyProperty指向的属性 -->
    <insert id="insertObject"
     parameterType="product"
     useGeneratedKeys="true"
     keyProperty="id">
        insert into
        <include refid="tableName" />
        (
        id,product_name,store,created,updated
        )
        values
        (
        null,#{productName},#{store},now(),now()
        )
    </insert>
    <update id="updateObject" parameterType="product">
        update
        <include refid="tableName"></include>
        <trim prefix="set" suffixOverrides=",">
            <if test="productName != null and productName != ''">
                product_name=#{productName},
            </if>
            <if test="store != null">
                store=#{store},
            </if>
            <if test="updated != null">
                updated=now(),
            </if>
        </trim>
        where id=#{id}
    </update>
    <delete id="deleteObject" parameterType="int">
        delete from
        <include refid="tableName" />
        where id=#{id}
    </delete>
</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 org.apache.ibatis.annotations.Param;

import com.project.pojo.Product;

public interface ProductDao {
    /**
     * 接口中方法名要与mapper文件中sqlid相同
     * 返回值类型要与sqlid对象的返回值类型匹配
     * @return
     */
    List<Product>findAll();
    
    Product findById(Integer id);
    
    Integer insertObject(Product product);
    
    List<Product> findProduct(@Param("columnName")String columnName);
    
    List<Product> findByName(String proudctName);
    
    Integer updateObject(Product product);
    
    Integer deleteObject(Integer id);
}

TestProduct.java

package com.project.test;

import java.io.IOException;
import java.util.Date;
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 findById()throws IOException{
        init();
        SqlSession session=factory.openSession();
        //通过session获取一个dao对象
        ProductDao dao = session.getMapper(ProductDao.class);
        Product product = dao.findById(1);
        System.out.println(product);
        //释放资源
        session.close();
    }
    public static void findByName()throws IOException{
        init();
        SqlSession session=factory.openSession();
        //通过session获取一个dao对象
        ProductDao dao = session.getMapper(ProductDao.class);
        List<Product> list = dao.findByName("apple");
        System.out.println(list);
        //释放资源
        session.close();
    }
    public static void findProduct()throws IOException{
        init();
        SqlSession session=factory.openSession();
        //通过session获取一个dao对象
        ProductDao dao = session.getMapper(ProductDao.class);
        List<Product> list = dao.findProduct("store");
        System.out.println(list);
        //释放资源
        session.close();
    }
    public static void insertObject()throws IOException{
        init();
        SqlSession session=factory.openSession(true);
        //通过session获取一个dao对象
        ProductDao dao = session.getMapper(ProductDao.class);
        Product product=new Product();
        product.setProductName("pineapple");
        product.setStore(70);
        Integer row=dao.insertObject(product);
        System.out.println(row);
        System.out.println(product);
        
        //释放资源
        session.close();
    }
    public static void updateObject()throws IOException{
        init();
        SqlSession session=factory.openSession(true);
        //通过session获取一个dao对象
        ProductDao dao = session.getMapper(ProductDao.class);
        Product product=new Product();
        product.setProductName("banana");
        product.setStore(20);
        product.setUpdated(new Date());
        product.setId(1);
        Integer row=dao.updateObject(product);
        System.out.println(row);
        //释放资源
        session.close();
    }
    public static void deleteObject()throws IOException{
        init();
        SqlSession session=factory.openSession(true);
        //通过session获取一个dao对象
        ProductDao dao = session.getMapper(ProductDao.class);
        Integer row=dao.deleteObject(2);
        System.out.println(row);
        //释放资源
        session.close();
    }

    public static void main(String[] args) {
        
        try {
            insertObject();
            System.out.println("============");
            findAll();
            System.out.println("============");
            findByName();
            System.out.println("============");
            updateObject();
            System.out.println("============");
            deleteObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        
        
    }
}

运行结果

1
Product [id=3, productName=pineapple, store=70, created=null, updated=null]
============
[Product [id=1, productName=apple, store=50, created=Tue Mar 19 00:00:00 CST 2019, updated=Tue Mar 19 00:00:00 CST 2019], Product [id=2, productName=pear, store=60, created=Tue Mar 19 00:00:00 CST 2019, updated=Tue Mar 19 00:00:00 CST 2019], Product [id=3, productName=pineapple, store=70, created=Tue Mar 19 00:00:00 CST 2019, updated=Tue Mar 19 00:00:00 CST 2019]]
============
[Product [id=1, productName=apple, store=50, created=Tue Mar 19 00:00:00 CST 2019, updated=Tue Mar 19 00:00:00 CST 2019], Product [id=3, productName=pineapple, store=70, created=Tue Mar 19 00:00:00 CST 2019, updated=Tue Mar 19 00:00:00 CST 2019]]
============
1
============
1

相关文章

网友评论

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

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