美文网首页
MyBatis以注解的方式实现sql 2

MyBatis以注解的方式实现sql 2

作者: 毛仑上保罗先生 | 来源:发表于2018-01-20 15:12 被阅读0次

    在上一个项目的基础上新建一个userMapperDao

    import org.apache.ibatis.annotations.Insert;
    
    public interface userMapperDao {
        //使用@Insert注解指明add方法要执行的SQL
        @Insert("insert into users(name, age) values(#{name}, #{age})")
        public int add(User user);
    }
    
    

    在config.xml中引入mapper

    <?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/mybatis" />
                    <property name="username" value="root" />
                    <property name="password" value="root" />
                </dataSource>
            </environment>
        </environments>
        <mappers>
             <mapper resource="userMapper.xml" />
             <mapper class="userMapperDao"/>
        </mappers>
    </configuration>
    

    注意是class
    <mapper class="userMapperDao"/>

    然后在main类中调用

    import org.apache.ibatis.session.SqlSession;
    
    import java.util.List;
    
    public class Main {
        public static void main(String[] args) {
            SqlSession SqlselectOne = MyBatisUtil.getSqlSessionFactory().openSession();
            String name = "userMapper.getUser";
            User user = SqlselectOne.selectOne(name, 1);
            SqlselectOne.close();
            SqlSession SqlselectList = MyBatisUtil.getSqlSessionFactory().openSession();
            String allUser = "userMapper.getAllUsers";
            List<User> users = SqlselectList.selectList(allUser);
            SqlselectList.close();
    
            /////////////////////////注解方式//////////////////////////
            SqlSession sqlAnnotation = MyBatisUtil.getSqlSessionFactory().openSession();
            userMapperDao mapperDao=sqlAnnotation.getMapper(userMapperDao.class);
            User objUser=new User();
            objUser.setAge(1);
            objUser.setName("1");
            mapperDao.add(objUser);
            sqlAnnotation.close();
        }
    }
    
    

    相关文章

      网友评论

          本文标题:MyBatis以注解的方式实现sql 2

          本文链接:https://www.haomeiwen.com/subject/ufjtaxtx.html