-
同时加载驱动包 mysql+mybatis
-
创建bean对应的mapper接口bookMapper
package com.imu.mzw.mapper; import java.util.List; import com.imu.mzw.bean.Book; public interface BookMapper { public void add(Book book); public List<Book> pagination(Integer pageIndex,Integer pageSize); }
-
编辑该接口对用的mapper.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.imu.mzw.mapper.BookMapper"> <select id="pagination" parameterType="int" resultType="Book"> select b_id bid,b_isbn bisbn,b_name bname, b_author bauthor,b_publisher bpublisher,b_price bprice, b_type btype,b_pic bpic,b_stock bstock, b_content bcontent from t_book limit #{0},#{1} </select> <insert id="add" parameterType="Book"> insert into t_book(b_isbn,b_name,b_author,b_publisher,b_price,b_type, b_pic,b_stock) values(#{bisbn},#{bname},#{bauthor},#{bpublisher}, #{bprice},#{btype},#{bpic},#{bstock}) </insert> </mapper>
-
配置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> <typeAliases> <!-- 包名扫描 --> <package name="com.imu.mzw.bean"/> </typeAliases> <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="jdbc:mysql://localhost:3306/db_imu?serverTimezone=GMT"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/imu/mzw/mapper/BookMapper.xml"/> </mappers> </configuration>
-
BaseDAO类
package com.imu.mzw.dao; import java.io.InputStream; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class BaseDAO { public SqlSession getSession() { SqlSession sqlSession=null; try { String resource="com/imu/mzw/config/mybatis-config.xml"; InputStream inputStream=Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); sqlSession = sqlSessionFactory.openSession(); System.out.println("conn mysql success"); } catch (Exception e) { System.err.println(e.getMessage()); } return sqlSession; } public static void main(String[] args) { //测试连接 new BaseDAO().getSession(); } }
-
运行测试