Maven Mybatis和数据库运用之查询

2019-12-04  本文已影响0人  池瑶瑶

pom.xml 新增

<dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.18</version>
        </dependency>

    </dependencies>

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.cj.jdbc.Driver"/>
                <property name="url" value="?"/>
                <property name="username" value="?"/>
                <property name="password" value="?"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
<!--        <package name="mapping/BookMapper.xml"/>-->
        <mapper resource="mapping/BookMapper.xml"/>
    </mappers>
</configuration>

resources.mapping.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.yao.mapper.BookMapper">
   <select id="loadBook" resultType="com.yao.pojo.Book">
   select * from books where id = #{id}
 </select>
</mapper>

Book.class

public class Book {
    private Integer id;
    private String name;

    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;
    }
}

BookMapper.class

public interface BookMapper {
    Book loadBook(int id);
}

Test1.class

public class Test1 {
    public static void main(String[] args) throws Exception{
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session=sqlSessionFactory.openSession(true);
        BookMapper mapper=session.getMapper(BookMapper.class);

        Book book=mapper.loadBook(1);
        System.out.println(book.getName());
        session.close();
    }
}

ps:注意路径的完整性

上一篇下一篇

猜你喜欢

热点阅读