MyBatis初体验(三)

MyBatis初体验(三)

  • SqlMapConfig.xml
  • jdbc.properties
  • pojo类
  • UserDao
  • 测试类
  • 一对一&延迟
  • 一对多
  • 动态语句
  • 逆向工程

注解方式使用MyBatis

SqlMapConfig.xml



<configuration>
    <properties resource="jdbc.properties">properties>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.user}"/>
                <property name="password" value="${jdbc.password}"/>
            dataSource>
        environment>
    environments>
    
    <mappers>
        <package name="com.tzt.dao">package>
    mappers>
configuration>

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybase?characterEncoding=utf8
jdbc.user=root
jdbc.password=root

pojo类

public class User {
     
    private Integer id;
    private String username;
    private String birthday;
    private String sex;
    private String address;
}//自行添加get,set方法

UserDao

public interface UserDao {
     
	@Select("select * from user")
		/*因为列与属性名不一致:映射结果集
		@Results 映射结果集的注解, 可以映射多列
		@Result: 映射一列
			属性:id =true 说明是主键 id=false不是主键(默认值)
		注意:如果列名与属性名一致,可以不配
		特殊的情况:某列使用两次或两次以上, 不论列名与属性名是否一致,必须@Result映射*/
	@Results({
     
	        @Result(id = true,column = "uid",property = "id")
	})
	List<User> findAll();
}

测试类

SqlSession sqlSession;
    @Before
    public void init() {
     
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("SqlMapConfig.xml");
        sqlSession = new SqlSessionFactoryBuilder().build(inputStream).openSession();
    }

    @Test
    public void findAll() {
     
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        List<User> list = mapper.findAll();
        for (User user : list) {
     
            System.out.println(user);
        }
    }

    @After
    public void close() {
     
        sqlSession.close();
    }

一对一&延迟

AccountDao

/**
 * 得到所有的账户:账户包含用户信息
 * @return
 */
@Select("select * from account")
  	//属性 :one  关联一个对象
  	//@One(select = "") : 对应一个对象   select (mapperId)
@Results({
     
        @Result(property = "u_id",column = "u_id"),
    	//特殊的情况:某列使用两次或两次以上, 不论列名与属性名是否一致,必须@Result映射
        @Result(property = "user",column = "u_id",javaType = User.class,
        one = @One(select = "com.tzt.dao.UserDao.findById",
                   fetchType = FetchType.LAZY))//设置延迟加载
})
public List<Account> findAll();

UserDao

@Select("select * from user where uid = #{id}")
@Results({
     
        @Result(id = true,column = "uid",property = "id")
})
public User findById(Integer id);

一对多

/**
 * 查询全部用户对象,包含账户信息
 * @return
 */
@Select("select * from user")
与xml不一样的地方'
   主键   javaType:必须是List.class
   xml:  ofType: pojo 类型
  javaType:可以省略的
@Results({
     
        @Result(id = true, column = "uid",property = "id"),
        @Result(property = "accountList",column = "uid",javaType = List.class,
        many = @Many(select = "com.itheima.dao.AccountDao.findByUserId",fetchType = FetchType.LAZY))//延迟加载
})
public List<User> findAll();

动态语句

UserDao

@SelectProvider(type = UserSqlProvider.class ,method = "findAll")
public List<User> findByCondition(User user);

UserSqlProvider

public String findAll(User user){
     
        StringBuffer sb = new StringBuffer();
        sb.append("select *  from user where 1=1 ");
        if(user.getUsername() != null){
     
            sb.append(" and username like \"%\"#{username}\"%\" ");
        }
        if(user.getAddress() != null){
     
            sb.append(" and address = #{address} ");
        }
        return sb.toString();
    }

逆向工程

逆向工程博客地址

你可能感兴趣的:(框架,MyBatis,学习,简单使用,入门,使用方式)