继上篇mybatis基础
https://blog.csdn.net/weixin_45262118/article/details/108482350
1.版本切换
- 切换环境 (environment)
<environments default="development">//dafault 默认使用的数据库id
<environment id="development">//数据库id
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
-
设置别名(大小写不能变)
<!--别名 配置数据库支持类--> <databaseIdProvider type="DB_VENDOR"> <property name="MySQL" value="mysql"/>//mysql为别名 <property name="Oracle" value="oracle"/> </databaseIdProvider>
-
z哎mapper.xml中写不同的数据库的SQL语句,并表明要使用的数据库别名
<select id="queryStudentById" resultType="student" parameterType="int" databaseId="mysql">//通过databaseId 调用数据库别名 select * from student where stuNo = #{id} </select>
如果既有不带databaseId的标签和带databaseId的标签,则数据库会优先使用带databaseId的标签
2.注解方式
- 在接口中,将要使用的SQL语句方法上写上注解**@Xxx("")**
@Select("select * from student where stuNo=#{stuNo}")
Student queryStudentById(int stuNo);
- 将接口的全类名写在mapper中,让MyBatis知道SQL语句此时是存储在接口中
注解/xml都支持批量引入
<mappers>
<!--<mapper resource="com/xiaoming/mapper/StudentMapper.xml"/>
<mapper class="com.xiaoming.mapper.StudentMapper"></mapper>-->
<package name="com.xiaoming.mapper"/>//写这句话就够了
</mappers>
3.增删改的返回值问题
返回值可以是void/Integer/Long/Boolean:只需要在接口中将返回值改变
4.事务的自动提交(推荐手工提交)
SqlSession sqlSession = sqlSessionFactory.openSession();
sqlSession.commit();//手动提交 进行增删改(dml)就要手动提交
SqlSession sqlSession = sqlSessionFactory.openSession(true);//自动提交 不需要commit
5.自增问题
- MySQL支持自增,ID数据类型为Integer 因为int默认 没数据时为 0
<insert id="addStudent" parameterType="student"
useGeneratedKeys="true" keyProperty="stuNo">//加入这两个属性即可
insert into student values(#{stuNo},#{stuName},#{stuAge},#{graName} )
</insert>
-
Oracle不支持自增: 通过序列模拟实现 序列自带两个属性:
-
nextval:序列中下一个值
-
currval:当前值
创建一个序列
-
create sequence myseq increment by 1 start with 1;
方式一:Befor(推荐) 创建SQL语句
<insert id="addStudent" parameterType="student" databaseId="oracle">
<selectKey keyProperty="stuNo" resultType="Integer" order="BEFORE">
select myseq.nextval from dual //dual 虚拟表
</selectKey>
insert into student values(#{stuNo},#{stuName},#{stuAge},#{graName} )
</insert>
方式二:After
<insert id="addStudent" parameterType="student" databaseId="oracle">
<selectKey keyProperty="stuNo" resultType="Integer" order="AFTER">
select myseq.currval from dual
</selectKey>
insert into student values(myseq.next ,#{stuName},#{stuAge},#{graName} )
</insert>
6.增加null
-
oracle: 如果插入的字段时Null.提示错误: other 而不是 null;
-
mysql:如果插入的字段时Null 可以执行(没有约束)
- 原因:各个数据库 在MyBatis中 对各种数据类型的默认值不一样
- mybatis中,jdbcTypeForNull(如果是null),则默认为other ,other对mysql能处理(null)oracle不能处理
<insert id="addStudent" parameterType="student" databaseId=