标签:void 并且 jpa ssi type star autoconf xtend int
目标:配置通用Mapper组件到Spring Boot项目中并使用 Mapper<T>接口
分析:通用Mapper:可以实现自动拼接sql语句,所有的mapper都不用编写任何方法也就是不用编写sql语句,可以提高效率
1.添加启动器依赖
2.改造UserMapper继承Mapper<User>
3.修改启动器引导类Application中的Mapper扫描注解
4.修改User实体类添加jpa注解
5.改造UserService实现业务功能
注意:在启动引导类上面的mapper扫描注解一定要修改为通用mapper的扫描注解(不然mapper找不到)
==========
1.添加启动器依赖
<!--通用mapper--> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>2.1.5</version> </dependency>
2.改造UserMapper继承Mapper<User>
package com.cc8w.home.mapper; import com.cc8w.com.cc8w.entity.User; import org.apache.ibatis.session.RowBounds; import tk.mybatis.mapper.common.Mapper; import java.util.List; public interface UserMapper extends Mapper<User> { }
3.修改启动器引导类Application中的Mapper扫描注解
package com.cc8w; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import tk.mybatis.spring.annotation.MapperScan; /** * spring boot 工程都有一个启动引导类, * 并且添加 @SpringBootApplication 组合注解 */ @SpringBootApplication //@MapperScan("com.cc8w.home.mapper") //扫描mapper接口 @MapperScan("com.cc8w.home.mapper")//使用通用mapper public class Application { public static void main(String[] args) { SpringApplication.run(Application.class,args); } }
4.修改User实体类添加jpa注解
package com.cc8w.com.cc8w.entity; import lombok.Data; import tk.mybatis.mapper.annotation.KeySql; import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.Table; @Data @Table(name="tb_users") public class User { @Id @KeySql(useGeneratedKeys = true) //id回填 private int id; @Column(name="user_name")//符合驼峰命名可以不用 private String userName; private String passWord; }
5.改造UserService实现业务功能
package com.cc8w.home.service; import com.cc8w.com.cc8w.entity.User; import com.cc8w.home.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class UserService { @Autowired private UserMapper userMapper; //根据id查询 public User queryById(int id){ return userMapper.selectByPrimaryKey(id); } //保存用户 @Transactional public void saveUser(User user){ userMapper.insertSelective(user); System.out.println("保存.."); } }
标签:void 并且 jpa ssi type star autoconf xtend int
原文地址:https://www.cnblogs.com/fps2tao/p/13821796.html