Mybatis添加数据

Mybatis添加数据

  1. 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做数据库的增删改必须手动提交事务

  1. 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
          }
      }
      

      这里报错是我故意的,用来测试是否自动回滚的代码⭐⭐⭐⭐⭐⭐

MyBatis添加数据可以通过以下步骤进行: 1. 创建一个 Java 类来表示你的数据模型,该类的属性应该与数据库表的字段一一对应。 ```java public class User { private int id; private String name; private int age; // 省略构造方法、Getter 和 Setter } ``` 2. 在 MyBatis 的配置文件中定义 SQL 映射语句,该语句用于将数据插入到数据库中。 ```xml <!-- UserMapper.xml --> <mapper namespace="com.example.UserMapper"> <insert id="insertUser" parameterType="com.example.User"> INSERT INTO users (id, name, age) VALUES (#{id}, #{name}, #{age}) </insert> </mapper> ``` 3. 创建一个接口来定义数据库操作的方法,该接口中的方法应该与 SQL 映射文件中定义的 id 一致。 ```java public interface UserMapper { void insertUser(User user); } ``` 4. 在代码中获取 MyBatis 的 SqlSession 对象,并调用对应的方法。 ```java public class Main { public static void main(String[] args) { // 获取 SqlSessionFactory SqlSessionFactory sqlSessionFactory = MyBatisUtils.getSqlSessionFactory(); // 获取 SqlSession try (SqlSession sqlSession = sqlSessionFactory.openSession()) { // 获取 Mapper 接口的实现类对象 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); // 创建一个 User 对象 User user = new User(); user.setId(1); user.setName("John"); user.setAge(25); // 调用插入方法 userMapper.insertUser(user); // 提交事务 sqlSession.commit(); } } } ``` 通过以上步骤,你就可以在 MyBatis 中成功添加数据数据库中了。请注意,这只是一个简单示例,实际项目中可能会有更多的配置和处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值