mybatis增刪改查(CRUD)

1、建立maven java web項目

2、建立src/test/java
        src/main/java
        src/main/resources

添加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>com.zit</groupId>
        <artifactId>mybatis04</artifactId>
        <version>1.0</version>
        <packaging>war</packaging>
        <name>mybatis04</name>
        <dependencies>

            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>4.0.0</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.servlet.jsp</groupId>
                <artifactId>jsp-api</artifactId>
                <version>2.2</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
            </dependency>

            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
                <scope>test</scope>
            </dependency>

            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.2</version>
                <scope>provided</scope>
            </dependency>

            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.11</version>
            </dependency>

            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.4.6</version>
            </dependency>
        </dependencies>
        <build>
            <finalName>${project.artifactId}</finalName>
            <testSourceDirectory>src/test/java</testSourceDirectory>
            <sourceDirectory>src/main/java</sourceDirectory>
            <!-- 處理無法加載資源配置文件 -->
            <resources>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.xml</include>
                        <include>**/*.properties</include>
                    </includes>
                </resource>
                <resource>
                    <directory>src/main/resources</directory>
                    <includes>
                        <include>**/*.xml</include>
                        <include>**/*.properties</include>
                    </includes>
                </resource>
            </resources>
        </build>

    </project>

3、修改src/main/webapp/WEB-INF/web.xml 文件
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
             version="4.0">
        <display-name>mybatis04</display-name>

        <!-- 配置web項目的web.xml文件的首頁 -->
        <welcome-file-list>
            <welcome-file>/show</welcome-file>
            <welcome-file>index.html</welcome-file>
            <welcome-file>index.jsp</welcome-file>
        </welcome-file-list>
    </web-app>

4、src/main/resources/db.properteis
        db.driver=com.mysql.cj.jdbc.Driver
        db.url=jdbc:mysql://localhost:3306/db?serverTimezone=PRC&useSSL=false&useUnicode=true&characterEncoding=utf8
        db.user=root
        db.password=

   src/main/resources/conf.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>
            <!-- 加載db.properties -->
            <properties resource="db.properties"/>

            <environments default="development">
                <environment id="development">
                    <transactionManager type="JDBC"/>
                    <dataSource type="POOLED">
                        <property name="driver" value="${db.driver}"/>
                        <property name="url" value="${db.url}"/>
                        <property name="username" value="${db.user}"/>
                        <property name="password" value="${db.password}"/>
                    </dataSource>
                </environment>
            </environments>
            <mappers>
                <package name="com.zit.mapper"/>
            </mappers>
        </configuration>

5、com.zit.mapper.BookMapper.java

package com.zit.mapper;

import com.zit.entity.Book;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;
/**
 * Created by webrx on 2018-09-19.
 */
public interface BookMapper {
    @Select("select * from book")
    public List<Book> query();

    @Select("select * from book where id=#{id}")
    public Book queryById(int id);

    @Insert("insert into book values(null,#{name},#{price},#{btime})")
    public int save(Book book);

    public int deleteById(int id);

    @Update("update book set name=#{name},price=#{price},btime=#{btime} where id=#{id}")
    public int update(Book book);


}

   
   com.zit.mapper.BookMapper.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.zit.mapper.BookMapper">
    <delete id="deleteById">
        delete from book where id = #{id}
    </delete>
</mapper>

package com.zit.entity;

import lombok.Data;

import java.math.BigDecimal;
import java.util.Date;

/**
 * Created by webrx on 2018-09-19.
 */
@Data
public class Book {
    private int id;
    private String name;
    private BigDecimal price;
    private Date btime;
}


   com.zit.dao.BookDAO.java 
package com.zit.dao;

import com.zit.entity.Book;
import com.zit.mapper.BookMapper;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

/**
 * Created by webrx on 2018-09-19.
 */
public class BookDAO implements BookMapper {
    private SqlSession session;
    private BookMapper bm;
    public BookDAO(){
        this.session = new MybatisHelper().getSession();
        bm = session.getMapper(BookMapper.class);
    }
    public List<Book> query() {
        return bm.query();
    }

    public int save(Book book) {
        int i = bm.save(book);
        session.commit();
        return i;
    }

    public int deleteById(int id) {
        int i = bm.deleteById(id);
        session.commit();
        return i;
    }

    public Book queryById(int id) {
        return bm.queryById(id);
    }

    public int update(Book book) {
        int i = bm.update(book);
        session.commit();
        return i;
    }
}



package com.zit.dao;

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;

/**
 * Created by webrx on 2018-09-19.
 */
public class MybatisHelper {
    protected SqlSessionFactory sf;
    protected SqlSession session;
    public MybatisHelper() {
        InputStream is = null;
        try {
            is = Resources.getResourceAsStream("conf.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        sf = new SqlSessionFactoryBuilder().build(is);
        session = sf.openSession();
    }

    public SqlSession getSession() {
        return session;
    }

    public SqlSessionFactory getFactory(){
        return sf;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章