MyBatis入门
1.环境搭建
-
① maven依赖
<!--MyBatis 3.4.2 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.2</version> </dependency> <!--MySQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency>
解决无法识别xml配置文件
<build> <resources> <resource> <!--<directory>src/test/java</directory>--> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources> </build>
② 导入mybatis-3.4压缩包中的lib下的所有jar包
-
由于MyBatis默认使用log4j输出日志信息,在类路径下建立 log4j.properties
# Global logging configuration log4j.rootLogger=ERROR, stdout # MyBatis logging configuration... 下行可更改 log4j.logger.com.itheima=DEBUG # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
-
存储变量文件db.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mybatis jdbc.username=root jdbc.password=
-
建立映射文件
<?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.itheima.mapper.CustomerMapper"> <!--抽出重复代码--> <sql id="customerColumns">id,username,jobs,phone</sql> <!--通过id查询用户--> <select id="findCustomerById" parameterType="Integer" resultType="com.itheima.po.Customer"> select <include refid="customerColumns"/> from t_customer where id = #{id} </select> </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> <properties resource="db.properties"/> <environments default="mysql"> <environment id="mysql"> <!--使用JDBC事务管理--> <transactionManager type="JDBC"/> <!--数据库连接池--> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <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/itheima/mapper/CustomerMapper.xml"/> </mappers> </configuration>
-
工具类创建SqlSession
public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory = null; static{ try{ Reader reader = Resources.getResourceAsReader("mybatis-config.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); }catch (Exception e){ e.printStackTrace(); } } public static SqlSession getSession(){ return sqlSessionFactory.openSession(); } }
-
测试程序(查询单个用户)
SqlSession sqlSession = MybatisUtils.getSession(); Customer customer = sqlSession.selectOne("com.itheima.mapper" + ".CustomerMapper.findCustomerById", 1); System.out.println(customer.toString()); sqlSession.close();
2.入门程序
1.模糊查询多个用户
<select id="findCustomerByName" parameterType="String"
resultType="com.itheima.po.Customer">
<!--select * from t_customer where username like '%${value}%' 下方防注入-->
select * from t_customer where username like concat('%',#{value},'%')
</select>
List<Customer> customers = sqlSession.selectList("com.itheima.mapper"
+ ".CustomerMapper.findCustomerByName", "j");
for(Customer customer: customers){
System.out.println(customer);
}
sqlSession.close();
2.添加用户
<insert id="addCustomer" parameterType="com.itheima.po.Customer"
keyProperty="id" useGeneratedKeys="true">
insert into t_customer(username,jobs,phone)
values (#{username},#{jobs},#{phone})
</insert>
SqlSession sqlSession = MybatisUtils.getSession();
Customer customer = new Customer();
customer.setUsername("rose");
customer.setJobs("student");
customer.setPhone("13333533092");
int rows = sqlSession.insert("com.itheima.mapper"
+".CustomerMapper.addCustomer",customer);
System.out.println(customer.getId());
if(rows>0){
System.out.println("插入了"+rows+"条数据");
}else{
System.out.println("插入失败");
}
sqlSession.commit();
sqlSession.close();
3.修改信息
<update id="updateCustomer" parameterType="com.itheima.po.Customer">
update t_customer set
username=#{username},jobs=#{jobs},phone=#{phone}
where id=#{id}
</update>
SqlSession sqlSession = MybatisUtils.getSession();
Customer customer = new Customer();
customer.setId(6);
customer.setUsername("rose");
customer.setJobs("programmer");
customer.setPhone("13311111111");
int rows = sqlSession.update("com.itheima.mapper"
+ ".CustomerMapper.updateCustomer", customer);
if(rows>0){
System.out.println("修改了"+rows+"条数据");
}else{
System.out.println("修改失败");
}
sqlSession.commit();
sqlSession.close();
4.删除用户
<update id="updateCustomer" parameterType="com.itheima.po.Customer">
update t_customer set
username=#{username},jobs=#{jobs},phone=#{phone}
where id=#{id}
</update>
int rows = sqlSession.delete("com.itheima.mapper"
+ ".CustomerMapper.deleteCustomer", 6);
if(rows>0){
System.out.println("删除了"+rows+"条数据");
}else{
System.out.println("删除失败");
}
sqlSession.commit();
sqlSession.close();
3.Mapper接口
SqlSession还有一个getMapper()方法用于访问Mybatis ,这个方法需要使用Mapper接口
Mapper接口规范
- Mapper接口名称与Mapper.xml名称必须一致
- Mapper接口的类路径和Mapper.xml映射文件相同
- 接口中的方法与xml中的id相同
- 方法的输入要和parameterType类型相同
- 输出要和resultType相同(如果使用了resultMap则与resultMap中的Type属性相同)
将上面配置文件写为Mapper接口形式
public interface CustomerMapper {
public Customer findCustomerById(Integer id);
public List<Customer> findCustomerByName(String name);
public int addCustomer(Customer customer);
public int updateCustomer(Customer customer);
public int deleteCustomer(Integer id);
}
程序调用方式
@Test
public void findCusByMapper(){
SqlSession sqlSession = MybatisUtils.getSession();
CustomerMapper customerMapper = sqlSession.getMapper(CustomerMapper.class);
List<Customer> customers = customerMapper.findCustomerByName("j");
for(Customer c:customers){
System.out.println(c);
}
sqlSession.close();
}