发表于: 2017-10-23 21:15:36
1 709
spring+mybatis整合
项目结构
运行结果
1;先是建立pojo
package com.dada.pojo;
public class Student
{
private int id;
private String name;
public int getId()
{
return id;
}
public void setId(int id)
{
2;mapper接口
public interface StudentMapper
{
public int add(Student student);
public void delete(int id);
public Student get(int id);
public int update(Student student);
public List<Student> list();
public int count();
3;mybatisd的student的xml文件
<mapper namespace="com.dada.mapper.StudentMapper">
<insert id="add" parameterType="Student">
insert into student (name) values(#{name})
</insert>
<delete id="delete" parameterType="Student">
delete from student where id = #{id}
</delete>
<select id="get" parameterType="int" resultType="Student">
select *from student where id = #{id}
</select>
<update id="update" parameterType="Student">
update student set name = #{name} where id= #{id}
</update>
<select id="list" resultType="Student">
select *from student
</select>
</mapper>
4;spring的applicationContext.xml文件
第一个bean数据库信息
<!--配置连接数据库的驱动,URL,账号和密码-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
第二个bean读取student.Xml
<!--扫描XML配置文件-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="typeAliasesPackage" value="com.dada.pojo"/>
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:com/dada/mapper/*.xml"/>
第三个bean扫描mapper
<!--扫描Mapper类-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.dada.mapper"/>
</bean>
5;注解测试spring
//表示这是一个Spring的测试类
@RunWith(SpringJUnit4ClassRunner.class)
//定位Spring的配置文件
@ContextConfiguration("classpath:applicationContext.xml")
public class MyTest
{
//给这个测试类装配Category对象
@Autowired
private StudentMapper studentMapper;
@Test
public void testAdd()
明日计划的事情:
继续学习spring和mybatis;尽量彻底搞懂
遇到的问题及解决方法:
1;主要还是语法理解不到位,概念不够清晰,慢慢补习
2;代码整体跑通,大致理解逻辑,但是部分概念代码意义不清晰,明天再学习一天,争取看通透
收获:
1;小课堂善后工作
2;spring+mybatis的第一次整合
评论