mybastis逆向工程

配置文件:generatorConfig.xml:

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

<!DOCTYPE generatorConfiguration

  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"

  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

 

<generatorConfiguration>

    <context id="testTables" targetRuntime="MyBatis3">

        <commentGenerator>

        

            <!-- 是否去除自动生成的注释 true:是 : false:否 -->

            <property name="suppressAllComments" value="true" />

        </commentGenerator>

        

        <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->

        <jdbcConnection driverClass="com.mysql.jdbc.Driver"

            connectionURL="jdbc:mysql:/localhost:3306/xx" userId="root"

            password="root">

        </jdbcConnection>

        <!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver"

            connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg"

            userId="yycg"

            password="yycg">

        </jdbcConnection> -->

 

        <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL和NUMERIC类型解析为java.math.BigDecimal -->

        <javaTypeResolver>

            <property name="forceBigDecimals" value="false" />

        </javaTypeResolver>

 

        <!-- targetProject:生成实体类的位置,重要!! -->

        <javaModelGenerator targetPackage="com.itheima.mybatis.po"

            targetProject=".\src">

            

            <!-- enableSubPackages:是否让schema作为包的后缀 -->

            <property name="enableSubPackages" value="false" />

            

            <!-- 从数据库返回的值被清理前后的空格 -->

            <property name="trimStrings" value="true" />

        </javaModelGenerator>

        

        <!-- targetProject:mapper映射文件生成的位置,重要!! -->

        <sqlMapGenerator targetPackage="com.itheima.mybatis.mapper" 

            targetProject=".\src">

            <property name="enableSubPackages" value="false" />

        </sqlMapGenerator>

        

        <!-- targetPackage:dao接口生成的位置,重要!! -->

        <javaClientGenerator type="XMLMAPPER"

            targetPackage="com.itheima.mybatis.dao" 

            targetProject=".\src">

            <property name="enableSubPackages" value="false" />

        </javaClientGenerator>

        

        <!-- 指定数据库表,要生成哪些表的代码,就写哪些表,要和数据库中对应,不能写错! -->

        <table tableName="sys_users"></table>

         </context>

</generatorConfiguration>

 

 

启动控制类:

package g;

 

import java.io.File;

import java.util.ArrayList;

import java.util.List;

import org.mybatis.generator.api.MyBatisGenerator;

import org.mybatis.generator.config.Configuration;

import org.mybatis.generator.config.xml.ConfigurationParser;

import org.mybatis.generator.internal.DefaultShellCallback;

 

 

public class GeneratorSqlmap {

 

 

 public void generator() throws Exception{

 

        List<String> warnings = new ArrayList<String>();

        boolean overwrite = true;

        //指定 逆向工程配置文件

        File configFile = new File("generatorConfig.xml");

        ConfigurationParser cp = new ConfigurationParser(warnings);

        Configuration config = cp.parseConfiguration(configFile);

        DefaultShellCallback callback = new DefaultShellCallback(overwrite);

        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,

                callback, warnings);

        myBatisGenerator.generate(null);

 

    }

    public static void main(String[] args) throws Exception {

        try {

            GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();

            generatorSqlmap.generator();

        } catch (Exception e) {

            e.printStackTrace();

        }

 

    }

}

### JDBC、MyBatis 和 JPA 集成使用教程 #### 1. 环境准备 为了实现JDBC、MyBatis以及JPA之间的集成,首先需要设置开发环境并引入必要的依赖项。假设项目基于Maven构建,则可以在`pom.xml`文件中添加如下依赖: ```xml <dependencies> <!-- MyBatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> <!-- JPA --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- MySQL Connector (或其他数据库驱动) --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- 其他必要依赖... --> </dependencies> ``` 上述配置确保了应用程序能够访问关系型数据库,并支持通过MyBatis和JPA两种方式操作数据[^1]。 #### 2. 数据源配置 在`application.properties`或`application.yml`中定义连接到目标数据库的数据源参数: 对于`.properties`文件: ```properties spring.datasource.url=jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=password spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver ``` 对于`.yml`文件: ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=UTC username: root password: password driver-class-name: com.mysql.cj.jdbc.Driver ``` 此部分设定允许程序利用统一的数据源来执行SQL查询语句或是ORM映射对象的操作。 #### 3. 实体类设计 创建实体类用于表示持久化层中的记录模型。这里以一个简单的用户(User)为例展示如何同时满足MyBatis和JPA的要求: ```java import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity(name = "users") // 表名指定为 users public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private Integer age; public User() {} public User(String name, Integer age){ this.name = name; this.age = age; } // Getter & Setter 方法... } ``` 这段代码片段展示了怎样编写既适用于JPA又兼容MyBatis的实体类结构。 #### 4. Mapper接口定义(针对MyBatis) 当采用MyBatis作为底层框架时,还需要额外提供Mapper接口以便于调用具体的CRUD方法: ```java @Mapper public interface UserMapper { @Select("SELECT * FROM users WHERE id=#{id}") User selectById(Long id); int insertUser(@Param("name")String name,@Param("age")Integer age); void updateUser(User user); boolean deleteUser(Long id); } ``` 以上即完成了基本的功能声明;实际业务逻辑则由对应的XML文件或者注解形式给出具体实现细节。 #### 5. Repository接口扩展(面向JPA) 如果倾向于使用更高级别的抽象——比如Spring Data JPA所提供的Repository模式的话,则可以这样继承自CrudRepository<T,ID>: ```java import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User,Long>{ List<User> findByName(String name); } ``` 这种方式下无需手动编码SQL语句即可完成大部分常见的增删改查动作。 #### 6. Service 层封装 无论是哪种技术栈的选择,在服务端都建议新增一层Service来进行事务管理及业务流程控制: ```java @Service @Transactional(readOnly=true) public class UserService { @Autowired private UserMapper mapper; @Autowired private UserRepository repository; public Optional<User> getUserById(Long userId){ return Optional.ofNullable(repository.findById(userId).orElse(mapper.selectById(userId))); } @Transactional public void saveOrUpdateUser(User user){ if(user.getId()==null || !repository.existsById(user.getId())){ mapper.insertUser(user.getName(),user.getAge()); }else{ mapper.updateUser(user); } } @Transactional public void removeUser(Long userId){ mapper.deleteUser(userId); repository.deleteById(userId); } } ``` 此处实现了混合运用两者API的能力,同时也体现了良好的分层架构设计理念。 #### 7. Controller 接口暴露RESTful API 最后一步就是对外公开HTTP请求入口点了,这通常会借助@Controller/@RestController这样的控制器组件来达成目的: ```java @RestController @RequestMapping("/api/users") public class UserController { @Autowired private UserService service; @GetMapping("/{userId}") public ResponseEntity<?> fetchOne(@PathVariable Long userId){ return service.getUserById(userId) .map(ResponseEntity::ok) .orElseGet(() -> ResponseEntity.notFound().build()); } @PostMapping("/") public ResponseEntity<Void> createNew(@RequestBody User newUser){ service.saveOrUpdateUser(newUser); URI location = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}").buildAndExpand(newUser.getId()).toUri(); return ResponseEntity.created(location).build(); } @PutMapping("/{userId}") public ResponseEntity<Void> updateExisting(@PathVariable Long userId, @RequestBody User updatedUser){ updatedUser.setId(userId); service.saveOrUpdateUser(updatedUser); return ResponseEntity.noContent().build(); } @DeleteMapping("/{userId}") public ResponseEntity<Void> deleteSpecific(@PathVariable Long userId){ service.removeUser(userId); return ResponseEntity.noContent().build(); } } ``` 综上所述,这套完整的案例不仅涵盖了从基础配置直至最终部署上线所需经历的主要环节,而且充分展现了不同工具链之间相互协作的可能性与灵活性。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值