欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

Mybatis的注解开发

时间:2023-06-09
Mybatis的注解开发 1、常用注解介绍 2、xml完成简单的crud

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?> insert into user values(#{id},#{username},#{password},#{birthday})

sqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>

接口

package com.dao;import com.domain.User;public interface UserMapper { public void save(User user);}

User类不变
改变MybatisTest文件

package com.test;import com.dao.UserMapper;import com.domain.User;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import org.junit.Before;import org.junit.Test;import java.io.IOException;import java.io.InputStream;public class MybatisTest { private UserMapper mapper; @Before public void before() throws IOException { InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml"); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); SqlSession sqlSession = sessionFactory.openSession(true); mapper = sqlSession.getMapper(UserMapper.class); } @Test public void testSave(){ User user=new User(); user.setUsername("mike"); user.setPassword("123"); mapper.save(user); }}

其余增删查改方法类似,看之前博客,然后再test方法里修改

3、注解开发完成基本的crud

删去包含UerMapper.xml的包

package com.dao;import com.domain.User;import org.apache.ibatis.annotations.Delete;import org.apache.ibatis.annotations.Insert;import org.apache.ibatis.annotations.Select;import org.apache.ibatis.annotations.Update;public interface UserMapper { @Insert("insert into user values(#{id},#{username},#{password},#{birthday})") public void save(User user); //@Update("update user set username=#{username},password=#{password} where id=#{id}") //@Delete("delete from user where id=#{id}") //@Select("select * from user"}

<?xml version="1.0" encoding="UTF-8" ?>

直接运行Test即可

4、一对一的注解开发



黑马程序员ssm框架视频P189-P190

5、一对多查询

P191

6、多对多查询

P192

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。