CREATE TABLE user ( id varchar(30) NOT NULL COMMENT '用户 openid', session_key varchar(30) DEFAULT NULL COMMENT '用户 session_key', nickname varchar(20) DEFAULT NULL COMMENT '用户昵称', role int(2) DEFAULT NULL COMMENT '角色类型 0是管理员,1是用户,2是员工', phone_number varchar(20) DEFAULT NULL COMMENT '用户手机号', create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', PRIMARY KEY (id), UNIQUE KEY phone_UNIQUE (phone_number) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表';和CREATE TABLE user_account ( id int(10) NOT NULL AUTO_INCREMENT, user_id varchar(30) CHARACTER SET utf8mb4 NOT NULL COMMENT '用户id', password varchar(50) COLLATE utf8mb4_bin NOT NULL COMMENT '用户密码', create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', PRIMARY KEY (id), KEY user_id_idx (user_id), CONSTRAINT user_id_idx FOREIGN KEY (user_id) REFERENCES user (id) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;,和public interface UserMapper extends MyBaseMapper<User> {},public interface UserAccountMapper extends MyBaseMapper<UserAccount> { },public interface MyBaseMapper<T> extends Mapper<T>, MySqlMapper<T>,MyInsertListMapper<T> { },如何插入?(不用jpa)
时间: 2024-03-28 11:42:19 浏览: 61
可以使用Mybatis进行插入操作。首先,在mapper.xml中编写插入语句:
```xml
<!-- 插入用户信息 -->
<insert id="insertUser" parameterType="User">
INSERT INTO user(id, session_key, nickname, role, phone_number)
VALUES(#{id}, #{sessionKey}, #{nickname}, #{role}, #{phoneNumber})
</insert>
<!-- 插入用户账户信息 -->
<insert id="insertUserAccount" parameterType="UserAccount">
INSERT INTO user_account(user_id, password)
VALUES(#{userId}, #{password})
</insert>
```
然后,在对应的Mapper接口中定义插入方法:
```java
public interface UserMapper {
void insertUser(User user);
}
public interface UserAccountMapper {
void insertUserAccount(UserAccount userAccount);
}
```
最后,在业务逻辑代码中调用插入方法即可:
```java
User user = new User();
user.setId("openid");
user.setSessionKey("session_key");
user.setNickname("nickname");
user.setRole(1);
user.setPhoneNumber("phone_number");
userMapper.insertUser(user);
UserAccount userAccount = new UserAccount();
userAccount.setUserId("openid");
userAccount.setPassword("password");
userAccountMapper.insertUserAccount(userAccount);
```
注意,如果使用的是Mybatis 3.5.0以上版本,可以直接使用@Insert注解代替在xml中编写插入语句。例如:
```java
@Insert("INSERT INTO user(id, session_key, nickname, role, phone_number) VALUES(#{id}, #{sessionKey}, #{nickname}, #{role}, #{phoneNumber})")
void insertUser(User user);
```
阅读全文