美文网首页
mybatis( MyBatis Spring-boot-sta

mybatis( MyBatis Spring-boot-sta

作者: jyjack | 来源:发表于2019-10-12 17:10 被阅读0次

    创建项目:

    image.png image.png image.png

    创建测试表

    在数据库中:创建测试表

    create table user
    (
        id bigint not null AUTO_INCREMENT comment '主键' primary key,
        age int null comment '年龄',
        password varchar(32) null comment '密码',
        sex int null comment '性别',
        username varchar(32) null comment '用户名'
    );
    

    配置数据源

    修改配置文件:配置数据源:application.yml

    spring:
      #profiles: dev
      datasource:
        url: jdbc:mysql://localhost:3306/helloworld?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
        username: root
        password: root
        driver-class-name: com.mysql.cj.jdbc.Driver
    

    编写代码

    创建实体类 User.java

    public class User {
        private Long id;
        private String username;
        private String password;
        private Integer age;
        private Integer sex;
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    
        public Integer getSex() {
            return sex;
        }
    
        public void setSex(Integer sex) {
            this.sex = sex;
        }
    
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    }
    

    创建访问接口 UserMapper ( 注意需要用 @Mapper注解)

    import com.example.demo4mybatis.entity.User;
    import org.apache.ibatis.annotations.Mapper;
    import org.apache.ibatis.annotations.Param;
    import org.apache.ibatis.annotations.Select;
    
    import java.util.List;
    
    @Mapper
    public interface UserMapper {
        @Select("select * from user")
        List<User> selectAll();
    
        @Select("select * from user where USERNAME= #{user_name} ")
        User selectByName(@Param("user_name") String userName);
    }
    

    测试代码

        @Autowired
        private UserMapper userMapper;
    
        @Test
        public void test() {
            List<User> list = userMapper.selectAll();
            System.out.println("--" + list.size());
    
            User user = userMapper.selectByName("张三丰");
            System.out.println("--" + user);
        }
    

    相关文章

      网友评论

          本文标题:mybatis( MyBatis Spring-boot-sta

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