万能Map
- UserMapper.java
// 万能Map
Integer addUserByMap(Map<String, Object> map;
- UserMapper.xml
<select id="addUserByMap" parameterType="map">
insert into mybatis.user (id,user,pwd) values (#{userid},#{username},#{password})
</select>
-
UserMapperTest.java
@Test public void addUserByMap() { try { SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); Map map = new HashMap(); map.put("userid", 3); map.put("username","yezihan"); map.put("password", "123456"); Integer res = userMapper.addUserByMap(map); System.out.println(res); sqlSession.close(); } catch (IOError e) { System.out.println(e); } }
模糊查询
-
UserMapper.java
// 模糊查询 List<User> getUserLike(String value);
-
UserMapper.xml
<!--模糊查询-->
<select id="getUserLike" resultType="top.yanggeol.pojo.User" parameterType="String">
select * from mybatis.user where user like #{value}
</select>
-
UserMapperTest.java
@Test public void getUserLike() { SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List<User> userList = userMapper.getUserLike("%i%"); for (User user : userList) { System.out.println(user); } sqlSession.close(); }
配置解析
核心配置
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
环境配置environments
可以配置多种环境,但每个SqlSessionFactory实例只能选择一种环境
属性properties
编写一个配置文件db.propertis
driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username = root
password = 123456
引入
<!--引入外部配置文件-->
<properties resource="db.properties"></properties>
类型别名
1.给实体类取别名
<!--给实体类取别名-->
<typeAliases>
<typeAlias type="top.yanggeol.entity.User" alias="User"/>
</typeAliases>
<select id="getUserList" resultType="User">
select * from mybatis.user
</select>
2.扫描实体类的包,它的默认别名就是这个类的类名,首字母小写
<typeAliases>
<package name="top.yanggeol.entity" />
</typeAliases>
3.使用注解定义别名
@Alias("User")
public class User{}
实体较少使用第一种 实体较多使用第二种
设置
这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为
映射器mappers
<!-- 使用相对于类路径的资源引用 -->
<mappers>
<mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
<mapper resource="org/mybatis/builder/BlogMapper.xml"/>
<mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>
<!-- 使用映射器接口实现类的完全限定类名 -->
<mappers>
<mapper class="org.mybatis.builder.AuthorMapper"/>
<mapper class="org.mybatis.builder.BlogMapper"/>
<mapper class="org.mybatis.builder.PostMapper"/>
</mappers>
<!-- 将包内
<!-- 将包内的映射器接口实现全部注册为映射器 -->
<mappers>
<package name="org.mybatis.builder"/>
</mappers>