1 、ActiveRecord
ActiveRecord(简称AR)一直广受动态语言( PHP 、 Ruby 等)的喜爱,而 Java 作为准静态语言,对于ActiveRecord 往往只能感叹其优雅,所以我们也在 AR 道路上进行了一定的探索,喜欢大家能够喜欢。
什么是ActiveRecord?
ActiveRecord也属于ORM(对象关系映射)层,由Rails最早提出,遵循标准的ORM模型:表映射到记录,记录映射到对象,字段映射到对象属性。配合遵循的命名和配置惯例,能够很大程度的快速实现模型的操作,而且简洁易懂。
ActiveRecord的主要思想是:
每一个数据库表对应创建一个类,类的每一个对象实例对应于数据库中表的一行记录;通常表的每个字段在类中都有相应的Field;
ActiveRecord同时负责把自己持久化,在ActiveRecord中封装了对数据库的访问,即CURD;;
ActiveRecord是一种领域模型(Domain Model),封装了部分业务逻辑;
1.1、开启AR之旅
在MP中,开启AR非常简单,只需要将实体对象继承Model即可。
package cn.itcast.mp.pojo; 1 import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.extension.activerecord.Model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor;
@Data @NoArgsConstructor @AllArgsConstructor public class User extends Model<User> {
1.2、根据主键查询
1.3、新增数据
private Long id; private String userName; private String password; private String name; private Integer age; private String email;
@RunWith(SpringRunner.class) @SpringBootTest public class UserMapperTest {
@Autowired private UserMapper userMapper;
@Test public void testAR() { User user = new User(); user.setId( 2 L); User user 2 = user.selectById(); System.out.println(user 2 ); }
@RunWith(SpringRunner.class) @SpringBootTest public class UserMapperTest {
@Autowired private UserMapper userMapper;
@Test public void testAR() { User user = new User(); user.setName("刘备"); user.setAge( 30 ); user.setPassword(" 123456 "); user.setUserName("liubei"); user.setEmail("liubei@itcast.cn");
boolean insert = user.insert();
System.out.println(insert);
结果:
1.5、更新操作
[main] [cn.itcast.mp.mapper.UserMapper.insert]-[DEBUG] ==> Preparing: INSERT INTO tb_user ( user_name, password, name, age, email ) VALUES ( ?, ?, ?, ?,? ) [main] [cn.itcast.mp.mapper.UserMapper.insert]-[DEBUG] ==> Parameters: liubei(String), 123456 (String), 刘备(String), 30 (Integer), liubei@itcast.cn(String) [main] [cn.itcast.mp.mapper.UserMapper.insert]-[DEBUG] <== Updates: 1
@RunWith(SpringRunner.class) @SpringBootTest public class UserMapperTest {
@Autowired private UserMapper userMapper;
@Test public void testAR() { User user = new User(); user.setId( 8 L); user.setAge( 35 );
boolean update = user.updateById(); System.out.println(update);}
1.6、删除操作
结果:
1.7、根据条件查询
[main] [cn.itcast.mp.mapper.UserMapper.updateById]-[DEBUG] ==> Preparing: UPDATE tb_user SET age=? WHERE id=? [main] [cn.itcast.mp.mapper.UserMapper.updateById]-[DEBUG] ==> Parameters: 35 (Integer), 8 (Long) [main] [cn.itcast.mp.mapper.UserMapper.updateById]-[DEBUG] <== Updates: 1
@RunWith(SpringRunner.class) @SpringBootTest public class UserMapperTest {
@Autowired private UserMapper userMapper;
@Test public void testAR() { User user = new User(); user.setId( 7 L);
boolean delete = user.deleteById(); System.out.println(delete); }}
[main] [cn.itcast.mp.mapper.UserMapper.deleteById]-[DEBUG] ==> Preparing: DELETE FROM tb_user WHERE id=? [main] [cn.itcast.mp.mapper.UserMapper.deleteById]-[DEBUG] ==> Parameters: 7 (Long) [main] [cn.itcast.mp.mapper.UserMapper.deleteById]-[DEBUG] <== Updates: 1
@RunWith(SpringRunner.class) @SpringBootTest public class UserMapperTest {
结果:
2 、Oracle 主键Sequence
在mysql中,主键往往是自增长的,这样使用起来是比较方便的,如果使用的是Oracle数据库,那么就不能使用自增长了,就得使用Sequence 序列生成id值了。
2.1、部署Oracle环境
为了简化环境部署,这里使用Docker环境进行部署安装Oracle。
@Autowired private UserMapper userMapper;
@Test public void testAR() { User user = new User(); QueryWrapper<User> userQueryWrapper = new QueryWrapper<>(); userQueryWrapper.le("age"," 20 ");
List<User> users = user.selectList(userQueryWrapper); for (User user 1 : users) { System.out.println(user 1 );} } }
[main] [cn.itcast.mp.mapper.UserMapper.selectList]-[DEBUG] ==> Preparing: SELECT id,user_name,password,name,age,email FROM tb_user WHERE age <=? [main] [cn.itcast.mp.mapper.UserMapper.selectList]-[DEBUG] ==> Parameters: 20 (String) [main] [cn.itcast.mp.mapper.UserMapper.selectList]-[DEBUG] <== Total: 2 1
User(id= 2 , userName=lisi, password= 123456 , name=李四, age= 20 , email=test 2 @itcast.cn, address=null) User(id= 6 , userName=caocao, password= 123456 , name=曹操, age= 20 , email=test@itcast.cn, address=null)
#拉取镜像 docker pull sath 89 /oracle- 12 c #创建容器 docker create - -name oracle - p 1521 : 1521 sath 89 /oracle- 12 c #启动 docker start oracle && docker logs - f oracle #下面是启动过程 Database not initialized. Initializing database. Starting tnslsnr
下面使用navicat12进行连接并操作oracle,使用资料中提供的安装包,可以试用 14 天。
需要注意的是:由于安装的Oracle是 64 位版本,所以navicat也是需要使用 64 为版本,否则连接不成功。
Copying database files 1 % complete 3 % complete 11 % complete 18 % complete 26 % complete 37 % complete Creating and starting Oracle instance 40 % complete 45 % complete 50 % complete 55 % complete 56 % complete 60 % complete 62 % complete Completing Database Creation 66 % complete 70 % complete 73 % complete 85 % complete 96 % complete 100 % complete Look at the log file "/u 01 /app/oracle/cfgtoollogs/dbca/xe/xe.log" for further details. Configuring Apex console Database initialized. Please visit http://#containeer: 8080 /em http://#containeer: 8080 /apex for extra configuration if needed Starting web management console
PL/SQL procedure successfully completed. Starting import from '/docker-entrypoint-initdb.d': ls: cannot access /docker-entrypoint-initdb.d/*: No such file or directory Import finished Database ready to use. Enjoy! ;)
#通过用户名密码即可登录
用户名和密码为: system/oracle
连接成功:
2.2、创建表以及序列
2.3、jdbc驱动包
由于版权原因,我们不能直接通过maven的中央仓库下载oracle数据库的jdbc驱动包,所以我们需要将驱动包安装到本地仓库。
安装完成后的坐标:
- -创建表,表名以及字段名都要大写
CREATE TABLE “TB_USER” (
“ID” NUMBER( 20 ) VISIBLE NOT NULL ,
“USER_NAME” VARCHAR 2 ( 255 BYTE) VISIBLE ,
“PASSWORD” VARCHAR 2 ( 255 BYTE) VISIBLE ,
“NAME” VARCHAR 2 ( 255 BYTE) VISIBLE ,
“AGE” NUMBER( 10 ) VISIBLE ,
“EMAIL” VARCHAR 2 ( 255 BYTE) VISIBLE
)
- -创建序列
CREATE SEQUENCE SEQ_USER START WITH 1 INCREMENT BY 1
#ojdbc 8 .jar文件在资料中可以找到
mvn install:install-file - DgroupId=com.oracle - DartifactId=ojdbc 8 - Dversion= 12. 1. 0. 1 - Dpackaging=jar - Dfile=ojdbc 8 .jar
2.4、修改application.properties
对于application.properties的修改,需要修改 2 个位置,分别是:
2.5、配置序列
使用Oracle的序列需要做 2 件事情:
第一,需要配置MP的序列生成器到Spring容器:
<dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc 8 </artifactId> <version> 12. 1. 0. 1 </version> </dependency>
#数据库连接配置
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver spring.datasource.url=jdbc:oracle:thin:@ 192. 168. 31. 81 : 1521 :xe spring.datasource.username=system spring.datasource.password=oracle
#id生成策略
mybatis-plus.global-config.db-config.id-type=input
package cn.itcast.mp; import com.baomidou.mybatisplus.extension.incrementer.OracleKeyGenerator; import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
@Configuration @MapperScan("cn.itcast.mp.mapper") //设置mapper接口的扫描包 public class MybatisPlusConfig {
/** * 分页插件 */ @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); }
/** * 序列生成器 */ @Bean public OracleKeyGenerator oracleKeyGenerator(){ return new OracleKeyGenerator();
第二,在实体对象中指定序列的名称:
2.6、测试
@KeySequence(value = "SEQ_USER", clazz = Long.class) public class User{ ...... }
package cn.itcast.mp; 1 import cn.itcast.mp.mapper.UserMapper; import cn.itcast.mp.pojo.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit 4 .SpringRunner;
import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest public class UserMapperTest {
@Autowired private UserMapper userMapper;
@Test public void testInsert(){ User user = new User(); user.setAge( 20 ); user.setEmail("test@itcast.cn"); user.setName("曹操"); user.setUserName("caocao"); user.setPassword(" 123456 ");
int result = this.userMapper.insert(user); //返回的result是受影响的行数,并不是自增 后的id System.out.println("result = " + result);
System.out.println(user.getId()); //自增后的id会回填到对象中 }
@Test public void testSelectById(){ User user = this.userMapper.selectById( 8 L); System.out.println(user); }