20220629_MyBatis_数据库增删改查练习(三)

文章目录


添加操作
第一步,接口加方法,不用返回值

void add(Brand brand);

映射文件里生成sql语句,如果要写sql语句时有自动提示,在一切设置完毕之后,必须用数据库名点表名,才能正确自动提示,可能是新版新特性

    <insert id="add">
        insert into mybatis.brand (brand_name, company_name, ordered, description, status)
        values (#{brandName},#{companyName},#{ordered},#{description},#{status})
    </insert>

执行代码,注意修改表项内容的sql,在mybatis里要手动提交,不然会rolling back,即使执行成功,数据库里查看也没有

    @Test
    public void testAdd() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        SqlSession sqs = sqlSessionFactory.openSession();

        BrandMapper mapper = sqs.getMapper(BrandMapper.class);

        int status = 1;
        String companyName = "nokia";
        String brandName = "aikon";
        Integer ordered = 16;
        String desc = "you never forget nokia";

        Brand br = new Brand();
        br.setStatus(status);
        br.setCompanyName(companyName);
        br.setBrandName(brandName);
        br.setDescription(desc);
        br.setOrdered(ordered);

        mapper.add(br);
        /**注意必须本方法执行后,必须手动提交*/
        sqs.commit();

        sqs.close();

    }

因为被回滚了两次添加,所以不回滚这次的id自动变成了6
请添加图片描述
如果要在添加表项后获得自动生成的id,把映射语句的标签加两个字段

    <insert id="add" useGeneratedKeys="true" keyProperty="id">
        insert into mybatis.brand (brand_name, company_name, ordered, description, status)
        values (#{brandName},#{companyName},#{ordered},#{description},#{status})
    </insert>

在方法执行之后用对象Brand的get方法获得id即可

        mapper.add(br);
        /**注意必须本方法执行后,必须手动提交*/
        sqs.commit();
        System.out.println(br.getId());

请添加图片描述

文章目录


修改操作
接口新建方法,获取返回值int,影响的行数

int update(Brand brand);

生成sql语句映射标签

    <update id="update">
        update mybatis.brand
        set brand_name = #{brandName},
            company_name = #{companyName},
            ordered = #{ordered},
            description = #{description},
            status = #{status}
        where id = #{id}
    </update>

写执行代码,这里我梦在会话的openSession(true)方法里加参数true,打开自动提交,就不用手动commit了

    @Test
    public void testUpdate() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        SqlSession sqs = sqlSessionFactory.openSession(true);

        BrandMapper mapper = sqs.getMapper(BrandMapper.class);

        int status = 1;
        String companyName = "Simon";
        String brandName = "siemens";
        Integer ordered = 17;
        String desc = "you still remember siemens";
        int id = 6;

        Brand br = new Brand();
        br.setStatus(status);
        br.setCompanyName(companyName);
        br.setBrandName(brandName);
        br.setDescription(desc);
        br.setOrdered(ordered);
        br.setId(id);

        int lines = mapper.update(br);
        System.out.println(lines);

        sqs.close();

    }

结果图
请添加图片描述

文章目录


动态修改,先把sql映射语句改成如下,关键字set换成标签

    <update id="update">
        update mybatis.brand
        <set>
            <if test="brandName != null and brandName != ''">
                brand_name = #{brandName},
            </if>
            <if test="companyName != null and companyName != ''">
                company_name = #{companyName},
            </if>
            <if test="ordered != null">
                ordered = #{ordered},
            </if>
            <if test="description != null and description != ''">
                description = #{description},
            </if>
            <if test="status != null">
                status = #{status}
            </if>
        </set>
        where id = #{id}
    </update>

执行代码里,就修改一个status

        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        SqlSession sqs = sqlSessionFactory.openSession(true);

        BrandMapper mapper = sqs.getMapper(BrandMapper.class);

        int status = 0;
        String companyName = "Simon";
        String brandName = "siemens";
        Integer ordered = 17;
        String desc = "you still remember siemens";
        int id = 6;

        Brand br = new Brand();
        br.setStatus(status);
//        br.setCompanyName(companyName);
//        br.setBrandName(brandName);
//        br.setDescription(desc);
//        br.setOrdered(ordered);
        br.setId(id);

        int lines = mapper.update(br);
        System.out.println(lines);

        sqs.close();

看日志预编译的语句,智能
请添加图片描述
结果图
请添加图片描述

以下是一个关于MyBatis的完整的增删改查练习题: 1. 创建一个名为`User`的Java类,它具有以下属性: ``` private int id; private String name; private String email; private String password; ``` 2. 创建一个名为`UserMapper`的MyBatis Mapper接口,它具有以下方法签名: ``` public List<User> findAll(); public User findById(int id); public void insert(User user); public void update(User user); public void delete(int id); ``` 3. 创建一个名为`UserMapper.xml`的MyBatis Mapper XML文件,它包含以下内容: ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.example.UserMapper"> <select id="findAll" resultType="com.example.User"> SELECT * FROM user; </select> <select id="findById" resultType="com.example.User"> SELECT * FROM user WHERE id=#{id}; </select> <insert id="insert" parameterType="com.example.User"> INSERT INTO user (name, email, password) VALUES (#{name}, #{email}, #{password}); </insert> <update id="update" parameterType="com.example.User"> UPDATE user SET name=#{name}, email=#{email}, password=#{password} WHERE id=#{id}; </update> <delete id="delete" parameterType="int"> DELETE FROM user WHERE id=#{id}; </delete> </mapper> ``` 4. 创建一个名为`UserDao`的Java类,它包含以下方法: ``` public List<User> findAll() throws IOException; public User findById(int id) throws IOException; public void insert(User user) throws IOException; public void update(User user) throws IOException; public void delete(int id) throws IOException; ``` 这些方法使用`SqlSession`对象从`UserMapper`接口中调用相应的方法。 5. 创建一个名为`MyBatisConfig.xml`的MyBatis配置文件,它包含以下内容: ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/mydatabase" /> <property name="username" value="root" /> <property name="password" value="mypassword" /> </dataSource> </environment> </environments> <mappers> <mapper resource="com/example/UserMapper.xml" /> </mappers> </configuration> ``` 6. 在`main`方法中,创建一个`SqlSessionFactory`对象,使用它创建一个`SqlSession`对象。然后,使用`UserDao`对象从数据库中执行一些操作,例如: ``` SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("MyBatisConfig.xml")); SqlSession session = sessionFactory.openSession(); UserDao userDao = session.getMapper(UserDao.class); List<User> userList = userDao.findAll(); User user = userDao.findById(1); userDao.insert(new User("John Doe", "john.doe@example.com", "password123")); userDao.update(new User(1, "Jane Doe", "jane.doe@example.com", "password456")); userDao.delete(2); session.commit(); session.close(); ``` 这些操作将查询所有用户,查询ID为1的用户,插入一个新用户,更新ID为1的用户,删除ID为2的用户,并提交更改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值