mybatis3.X入门学习demo
jdbc配置文件config.properties
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc\:mysql\://localhost\:3307/test?autoReconnect\=true&useUnicode\=true&characterEncoding\=utf8 jdbc.username=root jdbc.password=root
mybatis配置文件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> <properties resource="config.properties"/> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}" /> </dataSource> </environment> </environments> <mappers> <mapper resource="com/ibatis/pojo/user.xml" /> </mappers> </configuration>
User.java
package com.ibatis.pojo; public class User { public int id; public String username; public String password; public String address; public String ad; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getAd() { return ad; } public void setAd(String ad) { this.ad = ad; } }
user.xml实体
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd"> <mapper namespace="ddd"> <select id="getAllUsers" resultType="com.ibatis.pojo.User"> select * from user </select> </mapper>
数据库链接与数据操作代码
Reader reader = Resources.getResourceAsReader(resource); SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(reader); SqlSession session = ssf.openSession();try { List<User> selectList = session.selectList("ddd.getAllUsers"); int size = selectList.size(); System.out.println(size); System.out.println(selectList.get(0).getAddress()); } catch (Exception e) { e.printStackTrace(); } finally { session.close(); }