spring整合mybatis实现增删改查

学习了三天spring,现在我们可以做整合了

上代码吧

1:在pom.xml中添加spring-context、druid、mybatis、mysql-connector-java等基础依赖

 
            mysql
            mysql-connector-java
            8.0.26
        

        
            org.mybatis
            mybatis
            3.5.5

        

        
            org.springframework
            spring-jdbc
            5.2.10.RELEASE
        

        
            org.springframework
            spring-context
            5.2.10.RELEASE
        

        
            org.mybatis
            mybatis-spring
            1.3.0
        
        
            com.alibaba
            druid
            1.2.8
        

2:搭建三层架构

spring整合mybatis实现增删改查_第1张图片

dao层

/**
 * @author 王磊
 * @date 2022/4/28
 */
@Repository
public interface BrandsMapper {
    //查询所有
    @ResultMap("brandresultmap")
    @Select("select * from tb_brand")
    List selectAll();

    //单条件查询
    @ResultMap("brandresultmap")
    @Select("select * from tb_brand where id=#{id}")
    Brand selectByid(int id);

    //多条件动态查询
    List selectByids(Brand brand);

    //动态修改数据
    void update(Brand brand);

    //删除一个
    void deleteByid(int id);

    //批量删除
    void deleteByids(@Param("ids") int[] ids);

    //添加数据
    void add(Brand brand);
}

Service层

/**
 * @author 王磊
 * @date 2022/4/28
 */

public interface BrandService {
   //查询所有
   List selectAll();

   //条件查询
   Brand selectByid(int id);

   //多条件动态查询
   List selectByids(Brand brand);

   //动态修改数据
   void update(Brand brand);

   //删除一个
   void deleteByid(int id);

   //批量删除
   void deleteByids(int[] ids);

   void add(Brand brand);
}



实现类

**
 * @author 王磊
 * @date 2022/4/28
 */
@Service
public class BrandServiceImpl implements BrandService {

    @Autowired
    private BrandsMapper brandMapper;
    @Override
    public List selectAll() {
        List brands = brandMapper.selectAll();
        return brands;
    }

    @Override
    public Brand selectByid(int id) {
        Brand brand = brandMapper.selectByid(id);
        return brand;
    }

    @Override
    public List selectByids(Brand brand) {
        List brands = brandMapper.selectByids(brand);
        return brands;
    }

    @Override
    public void update(Brand brand) {
        brandMapper.update(brand);
    }

    @Override
    public void deleteByid(int id) {
        brandMapper.deleteByid(id);
    }

    @Override
    public void deleteByids(int[] ids) {
        brandMapper.deleteByids(ids);
    }

    @Override
    public void add(Brand brand) {
        brandMapper.add(brand);
    }
}

domain层

/**
 * @author 王磊
 * @date 2022/4/28
 */
public class Brand {

    /**
     * 品牌实体类
     */
        // id 主键
        private Integer id;
        // 品牌名称
        private String brandName;
        // 企业名称
        private String companyName;
        // 排序字段
        private Integer ordered;
        // 描述信息
        private String description;
        // 状态:0:禁用  1:启用
        private Integer status;

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getBrandName() {
            return brandName;
        }

        public void setBrandName(String brandName) {
            this.brandName = brandName;
        }

        public String getCompanyName() {
            return companyName;
        }

        public void setCompanyName(String companyName) {
            this.companyName = companyName;
        }

        public Integer getOrdered() {
            return ordered;
        }

        public void setOrdered(Integer ordered) {
            this.ordered = ordered;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public Integer getStatus() {
            return status;
        }

        public void setStatus(Integer status) {
            this.status = status;
        }

    @Override
    public String toString() {
        return "Brand{" +
                "id=" + id +
                ", brandName='" + brandName + '\'' +
                ", companyName='" + companyName + '\'' +
                ", ordered=" + ordered +
                ", description='" + description + '\'' +
                ", status=" + status +
                '}';
    }
}

controller层


/**
 * @author 王磊
 * @date 2022/4/28
 */
@Controller
public class BrandController {
    @Autowired
    private BrandService brandService;

    //查询所有
    public List selectAll() {
        return brandService.selectAll();
    }

    //条件查询
    public Brand selectByid(int id) {
        return brandService.selectByid(id);
    }

    //多条件动态查询
    public List selectByids(Brand brand) {
        String brandName = brand.getBrandName();
        String companyName = brand.getCompanyName();
        if (brandName!=null && brandName!=""){
            brandName="%"+brandName+"%";
            brand.setBrandName(brandName);
        }

        if (companyName!=null && companyName!=""){
            companyName="%"+companyName+"%";
            brand.setCompanyName(companyName);
        }

        return brandService.selectByids(brand);
    }

    //动态修改数据
    public void update(Brand brand){
        brandService.update(brand);
    }

    //删除一个
    public void deleteByid(int id){
        brandService.deleteByid(id);
    }

    //批量删除
    public void deleteByids(int[] ids){
        brandService.deleteByids(ids);
    }

    //添加数据
    public void add(Brand brand){
        brandService.add(brand);
    }
}

xml文件





    
    
        
        
    
    
        insert into tb_brand (brand_name,company_name,ordered,description,status)
        values(#{brandName},#{companyName},#{ordered},#{description},#{status})
    

    
    
        update tb_brand
        
            
                brand_name=#{brandName},
            
            
                company_name=#{companyName},
            
            
                ordered=#{ordered},
            
            
                description=#{description},
            
            
                status=#{status}
            
        
        where id = #{id};
    

    
        delete from tb_brand where id=#{id}
    

    
        delete from tb_brand where id in
        
            #{id}
        
    

    
    


好了,最重要的来了,配置文件类

首先先准备jdbc.properties文件

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=root

然后jdbc配置类

我们要获取一个 dataSource对象,spring有一个注解叫Bean作用:方法的返回值交给spring管理


/**
 * @author 王磊
 * @date 2022/4/28
 */
public class JdbcConfig {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String userName;
    @Value("${jdbc.password}")
    private String password;

    @Bean
    public DataSource dataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(userName);
        ds.setPassword(password);
        return ds;
    }
}

接下来是Mybatis的配置类

/**
 * @author 王磊
 * @date 2022/4/28
 */
public class MybatisConfig {
        //定义bean,SqlSessionFactoryBean,用于产生SqlSessionFactory对象
        @Bean
        public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
            SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
            //实体类
            ssfb.setTypeAliasesPackage("com.xxx.domain");
            ssfb.setDataSource(dataSource);
            return ssfb;
        }
        //定义bean,返回MapperScannerConfigurer对象
        @Bean
        public MapperScannerConfigurer mapperScannerConfigurer(){
            MapperScannerConfigurer msc = new MapperScannerConfigurer();
            msc.setBasePackage("com.xxx.dao");//接口
            return msc;
        }
}

最后,spring配置类

**
 * @author 王磊
 * @date 2022/4/28
 */
@Configuration//声明这是一个配置类
@ComponentScan("com.itheima")//包扫描
@PropertySource("classpath:jdbc.properties")//加载配置文件
@Import({JdbcConfig.class,MybatisConfig.class})//导入外部构造类
public class SpringConfig {}

测试类

/**
 * @author 王磊
 * @date 2022/4/28
 */
public class app {
    public static void main(String[] args) {
        ApplicationContext context = new             
    AnnotationConfigApplicationContext(SpringConfig.class);

        BrandController Controller = context.getBean(BrandController.class);
        //查询所有
        //  List brands = Controller.selectAll();
              System.out.println(brands);


        //条件查询
         Brand brand =Controller.selectByid(4);
        System.out.println(brand);
       

     //多条件动态查询-
        Brand brand = new Brand();
        brand.setBrandName("阿里");
        List brands1 = Controller.selectByids(brand);
        System.out.println(brands1);

        //动态修改数据
        Brand brand = new Brand();
        brand.setId(4);
        brand.setBrandName("字节跳动");
        Controller.update(brand);

        //删除一个
        Controller.deleteByid(5);

        //批量删除
        int[] arr = {6, 7, 8};
        Controller.deleteByids(arr);


        //添加数据
        Brand brand = new Brand();
        brand.setBrandName("软通动力");
        brand.setCompanyName("软通动力有限公司");
        brand.setOrdered(20);
        brand.setDescription("知名外包公司");
        brand.setStatus(1);
        Controller.add(brand);
    }
}

完美收工,spring整合mybatis是我们必须要掌握的本领,日更,有不懂的欢迎留言

你可能感兴趣的:(spring,spring,java,intellij-idea)