创建Java项目,导入相应jar包
新建xml配置文件
-
sqlMapConfig.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.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="./user.xml"/> </mappers> </configuration>
创建与数据库相对应的实体类
-
User.java
package com.entity; import java.util.Date; public class User { private int id; private String username; private Date birthday; private String sex; private String address; 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 Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public User(int id, String username, Date birthday, String sex, String address) { super(); this.id = id; this.username = username; this.birthday = birthday; this.sex = sex; this.address = address; } public User() { super(); } }
创建与实体类相对应的xml解析文件
-
user.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"> <!-- namespace:命名空间 作用对sql语句进行分类管理 --> <mapper namespace="baiyun"> <!-- 根据用户id查询用户信息 --> <!-- id:唯一标识sql语句 parameterType:制定输入参数类型 #{}:代表一个占位符,参数名任意 resultType:指定查询结果集映射的java对象类型 --> <select id="selectUserById" parameterType="int" resultType="com.entity.User"> select * from user where id = #{id} </select> </mapper>
进行查询测试
- Test.java
package com.test; import java.io.IOException; 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; import com.entity.User; public class Test1 { public static void main(String[] args) throws IOException { //创建SqlSessionFactoryBuilder SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder(); //读取配置文件 InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml"); //创建SqlSessionFactory SqlSessionFactory factory = ssfb.build(inputStream); //创建sqlsession SqlSession session = factory.openSession(); /* * 参数:namespace.id名 * 查询语句的输入参数 * */ //执行查询 User user = session.selectOne("baiyun.selectUserById",1); //关闭session session.close(); System.out.println(user); } }
-
-