利用Mybatis插入数据到MySQL中

这篇博客详细介绍了如何使用Mybatis框架将数据插入到MySQL数据库中,从导入必要的jar包开始,涵盖数据库设置、SqlSession Bean配置、mybatis配置文件、实体类创建、实体类与mybatis映射的步骤,最后通过测试验证了整个流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、需要导入的jar包

         <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.11.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.3</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.18</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.14</version>
        </dependency>

二、数据库的设置和 SqlSession Bean

<bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:database.properties</value>

            </list>
        </property>
    </bean>

    <!--BI 商品推荐数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>

        <!--链接池初始化线程数据-->
        <property name="initialSize" value="${jdbc.initialPoolSize}" />
        <!--链接池最小线程数-->
        <property name="minIdle" value="${jdbc.minPoolSize}" />
        <!--链接池最大线程数-->
        <property name="maxActive" value="${jdbc.maxPoolSize}" />
        <!--获取链接超时时间-->
        <property name="maxWait" value="${jdbc.maxWaitTime}" />
        <!--间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒-->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!--一个连接在池中最小生存的时间,单位是毫秒-->
        <property name="minEvictableIdleTimeMillis" value="300000" />
        <property name="validationQuery" value="SELECT 'x'" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />

        <!--打开PSCache,并且指定每个连接上PSCache的大小-->
        <property name="poolPreparedStatements" value="false" />
        <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />

    </bean>



    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <!--mybatis的配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml" />
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory" />
    </bean>

三、mybatis配置文件

<configuration>

    <mappers>
         <mapper resource="supplierProductMapper.xml"/>
    </mappers>
</configuration>    

四、实体类

public class SupplierProduct {
    private int id;
    private int supplierId;
    private String createdAt;
    private String updatedAt;
    private String deletedAt;
    private int isDeleted;
    //省略get、set方法

五、实体类与mybatis的映射

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.jolly.spider.bean.supplierProductMapper" >


<!--返回自增的id-->
    <insert id="insert" useGeneratedKeys="true" keyProperty="id" parameterType="com.jolly.spider.bean.SupplierProduct">
        INSERT INTO
           supplier_product
        (
            supplier_id,created_at,updated_at,process_status,is_deleted,supp_parent_id,supp_parent_code,
            name,
            description,category,image_url,image_list,extra,currency
        )VALUES(
            #{supplierId},#{createdAt},#{updatedAt},#{processStatus},#{isDeleted},#{suppParentId},#{suppParentCode},#{name},
            #{description},#{category},#{imageUrl},#{imageList},#{extra},#{currency}

        )
    </insert>
</mapper>

六、测试

private final static String SPACE="com.jolly.spider.bean.supplierProductMapper";
    private static String path="database.config.xml";
    private SqlSessionTemplate sqlSession;

    public SupplierDao(){
        ApplicationContext context=new ClassPathXmlApplicationContext(path);
        sqlSession=(SqlSessionTemplate) context.getBean("sqlSession");

    }

    public int insert(SupplierProduct sp){
        try{
            return sqlSession.insert(SPACE+".insert",sp);
        }catch (Exception e){
            e.printStackTrace();
        }
       return -1;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值