第一步:先配置mybatis配置
<?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> <typeAlias alias="Users" type="orm.Users"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?characterEncoding=utf-8" /> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <mapper resource="orm/Users.xml"/> </mappers> </configuration>
第二步:创建一个实体对象
package orm; public class Users { private Integer id; private String username; private String password; private Integer age; private Integer sex; public Users(Integer id, String username, String password, Integer age, Integer sex) { super(); this.id = id; this.username = username; this.password = password; this.age = age; this.sex = sex; } //此处必须添加一个无参构造 public Users() { } //set和get省略 @Override public String toString() { // TODO Auto-generated method stub return super.toString(); } }
第三步:配置一个简单的查询参数
<?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="orm.Users"> <select id="selectUserByID" parameterType="int" resultType="orm.Users"> select * from Users where id = #{id} </select> </mapper>
第四步:测试(简洁版)
String resString="Configuration.xml"; Reader reader = Resources.getResourceAsReader(resString); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession session = sessionFactory.openSession(); String statement ="orm.Users.selectUserByID"; Users users = (orm.Users) session.selectOne(statement,2); System.out.println(users.getUsername());
第四步:测试(完成版)
public class Test { private static SqlSessionFactory sqlSessionFactory; private static Reader reader; static{ try{ reader = Resources.getResourceAsReader("Configuration.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); }catch(Exception e){ e.printStackTrace(); } } public static SqlSessionFactory getSession(){ return sqlSessionFactory; } public static void main(String[] args) { SqlSession session = sqlSessionFactory.openSession(); try { Users users = (Users) session.selectOne("orm.Users.selectUserByID", 2); System.out.println(users); } finally { session.close(); } } }
时间: 2024-11-11 18:26:49