Mybatis添加数据
/**
* 新增
*/
@Test
public void testInsert(){
try {
//1. 加载配置文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
//2. 获取SqlSession工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//3. 获取sqlsession
SqlSession sqlSession = sqlSessionFactory.openSession();
//4. 获取dao接口对应的mapper
UserDao userDao = sqlSession.getMapper(UserDao.class);
User user = new User();
user.setUserName("zhangsan");
//5. 调用添加的方法()
userDao.addUser(user);
//6. 增删改操作需要提交事务
sqlSession.commit();
sqlSession.close();
} catch (IOException e) {
e.printStackTrace();
}
}
mybatis做数据库的增删改必须手动提交事务
-
SSM整合步骤
<!-- spring-beans --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.3.18.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.18.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.18.RELEASE</version> </dependency> <!--fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.75</version> </dependency> <!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <!--mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <!-- mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.2</version> </dependency> <!-- druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.12</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.18.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-tx --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.3.18.RELEASE</version> </dependency>
-
配置web.xml
<filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mybatis.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
-
配置spring-mybatis.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--扫描所有包--> <context:component-scan base-package="com.qianfeng"></context:component-scan> <!--导入mvc配置--> <import resource="classpath:spring-mvc.xml"/> <!--数据源:druid连接池--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/db_mybatis_test"></property> <property name="username" value="root"></property> <property name="password" value="root"></property> </bean> <!--配置sqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--数据源--> <property name="dataSource" ref="dataSource"></property> <!--引入了mybatis的配置文件--> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <!--mapper文件所在的位置--> <property name="mapperLocations" value="classpath:mappers/*.xml"></property> </bean> <!--配置mapper对应的dao接口--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--dao接口所在的包名--> <property name="basePackage" value="com.qianfeng.dao"></property> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <!--使用的是jdbc的事务--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!--事务管理声明式 注解驱动--> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
-
配置spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--扫描--> <context:component-scan base-package="com.qianfeng"></context:component-scan> <!--释放所有的静态资源--> <mvc:default-servlet-handler/> <!--注解驱动标签: 将前端浏览器请求url与后端controller中的requestMapping映射相匹配 解决添加释放静态资源之后访问后端映射报404的问题 --> <mvc:annotation-driven> <mvc:message-converters register-defaults="false"> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json;charset=utf-8</value> <!--为了避免低版本ie浏览器获取json数据时出现文件下载的情况--> <value>text/html;charset=utf-8</value> </list> </property> <!--解决当属性为null时,如何返回数据--> <property name="features"> <list> <value>WriteNullNumberAsZero</value> <value>WriteNullStringAsEmpty</value> <value>WriteNullListAsEmpty</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> </beans>
-
配置mybatis-config
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!--打印执行的SQL语句--> <settings> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> <!--配置pojo类的别名:在所有的mapper文件中,pojo实体类都不需要配置包名--> <typeAliases> <package name="com.qianfeng.pojo"></package> </typeAliases> </configuration>
-
测试查询用户列表
@Controller @RequestMapping("/user") public class UserController { @Resource private UserService userService; @RequestMapping("/list") @ResponseBody public List<User> userList(){ return userService.getUserList(); } }
-
添加用户测试事务自动回滚
@Service @Transactional //添加次注解,当出现异常时,事务会自动回滚 public class UserServiceImpl implements UserService { @Resource private UserDao userDao; @Override public void add(User user) { userDao.addUser(user); //张三扣1000 System.out.println(1/0); //报异常(服务器炸了) userDao.addUser(user);//李四加1000 } }
这里报错是我故意的,用来测试是否自动回滚的代码⭐⭐⭐⭐⭐⭐
-