Realm学习笔记

先决条件(环境要求)

1.Android Studio 版本1.5.1或更高版本
2.JDK 7.0或更高版本
3.Android SDK的近期版本
4.Android API 大于等于9(Android 2.3以上)

注意:Realm不独立支持java,我们不再支持Eclipse作为IDE;请使用Android Studio集成


安装

通过Gradle安装Realm插件
第一步:添加class path依赖到工程级别的build.gradle文件中

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath "io.realm:realm-gradle-plugin:6.0.2"
    }
}

第二步:应用realm-android插件到应用级别build.gradle文件的顶部

apply plugin: 'realm-android'

一旦你完成了这两次修改,刷新你的gradle依赖。如果你是从realm早期版本更新过来的话你需要使用./gradlew clean一下项目


其它构建

maven和ant构建目前是不被支持的
混淆配置已经在Realm库中了不需要额外配置


例子

Realm Java 让你高效的编写app模型层更安全,持久并且更快。如下:

// Define your model class by extending RealmObject
public class Dog extends RealmObject {
    private String name;
    private int age;

    // ... Generated getters and setters ...
}

public class Person extends RealmObject {
    @PrimaryKey
    private long id;
    private String name;
    private RealmList<Dog> dogs; // Declare one-to-many relationships

    // ... Generated getters and setters ...
}

// Use them like regular java objects
Dog dog = new Dog();
dog.setName("Rex");
dog.setAge(1);

// Initialize Realm (just once per application)
Realm.init(context);

// Get a Realm instance for this thread
Realm realm = Realm.getDefaultInstance();

// Query Realm for all dogs younger than 2 years old
final RealmResults<Dog> puppies = realm.where(Dog.class).lessThan("age", 2).findAll();
puppies.size(); // => 0 because no dogs have been added to the Realm yet

// Persist your data in a transaction
realm.beginTransaction();
final Dog managedDog = realm.copyToRealm(dog); // Persist unmanaged objects
Person person = realm.createObject(Person.class); // Create managed objects directly
person.getDogs().add(managedDog);
realm.commitTransaction();

// Listeners will be notified when data changes
puppies.addChangeListener(new OrderedRealmCollectionChangeListener<RealmResults<Dog>>() {
    @Override
    public void onChange(RealmResults<Dog> results, OrderedCollectionChangeSet changeSet) {
        // Query results are updated in real time with fine grained notifications.
        changeSet.getInsertions(); // => [0] is added.
    }
});

// Asynchronously update objects on a background thread
realm.executeTransactionAsync(new Realm.Transaction() {
    @Override
    public void execute(Realm bgRealm) {
        Dog dog = bgRealm.where(Dog.class).equalTo("age", 1).findFirst();
        dog.setAge(3);
    }
}, new Realm.Transaction.OnSuccess() {
    @Override
    public void onSuccess() {
        // Original queries and Realm objects are automatically updated.
        puppies.size(); // => 0 because there are no more puppies younger than 2 years old
        managedDog.getAge();   // => 3 the dogs age is updated
    }
});

浏览Realm数据库

如果你需要查找你应用的Realm文件,请看StackOverflow answer里的详细介绍。


Realm Studio

Realm Studio是我们首个开发者工具,你可以通过它很容易的管理Realm数据库和Realm平台。通过RealmStudio ,你可以打开并编辑SyncedRealms和管理任何Realm 对象服务实例。它支持Mac,Windows和Linux

Stetho Realmhttps://github.com/uPhyca/stetho-realmicon-default.png?t=L892https://github.com/uPhyca/stetho-realm

facebook开发的一个android debug 桥,基于chrome brower


初始化Realm

在开始在你的app中使用Realm之前,你必须初始化它。只需要初始化一次就好

Realm.init(context);

你必须提供一个Android的应用上下文Context。在Appplication的子类onCreate方法中初始化它是个好的位置。

public class MyApplication extends Application {
  @Override
  public void onCreate() {
    super.onCreate();
    Realm.init(this);
  }
}

如果你创建你自己的Application子类,你需要添加它到清单文件当中AndroidManifest.xml:

<application
  android:name=".MyApplication"
  ...
/>

Realms

一个Realm是一种Realm移动数据库容器的一个实例。Realms可以是本地的或同步的。同步的Realm使用Realm Object Server透明地将其内容与其他设备同步。当您的应用程序继续像本地文件一样继续使用同步的Realm时,该Realm中的数据可能会被具有对该Realm写入权限的任何设备更新。实际上,您的应用程序可以与本地或同步的任何Realm相同的方式工作。(see you later)

关于Realm更详细的说明https://realm.io/docs/data-modelicon-default.png?t=L892https://realm.io/docs/data-model

开放Realms

通过实例化一个新的Realm对象打开Realm。我们已经在示例中看过这种用法。

// Initialize Realm
Realm.init(context);

// Get a Realm instance for this thread
Realm realm = Realm.getDefaultInstance();

通过getDefaultInstance方法实例化的Realm伴随着一个默认配置


配置Realm

使用RealmConfiguration对象来控制Realms的创建配置。Realm可用的最小的配置如下:

RealmConfiguration config = new RealmConfiguration.Builder().build();

该配置(不带任何选项)使用名为default.realm位于Context.getFilesDir中的Realm文件。要使用其他配置,您将创建一个新RealmConfiguration对象:

// The RealmConfiguration is created using the builder pattern.
// The Realm file will be located in Context.getFilesDir() with name "myrealm.realm"
RealmConfiguration config = new RealmConfiguration.Builder()
  .name("myrealm.realm")
  .encryptionKey(getKey())
  .schemaVersion(42)
  .modules(new MySchemaModule())
  .migration(new MyMigration())
  .build();
// Use the config
Realm realm = Realm.getInstance(config);

您可以具有多个RealmConfiguration对象,那样可以独立控制每个Realm的版本,架构和位置。

RealmConfiguration myConfig = new RealmConfiguration.Builder()
  .name("myrealm.realm")
  .schemaVersion(2)
  .modules(new MyCustomSchema())
  .build();

RealmConfiguration otherConfig = new RealmConfiguration.Builder()
  .name("otherrealm.realm")
  .schemaVersion(5)
  .modules(new MyOtherSchema())
  .build();

Realm myRealm = Realm.getInstance(myConfig);
Realm otherRealm = Realm.getInstance(otherConfig);

通过使用Realm.getPath获取Realm的绝对路径。

重要的是要注意Realm实例是线程单例,这意味着静态构造函数将响应来自给定线程的所有调用而返回相同的实例。


默认Realm

该RealmConfiguration可以保存为默认配置。在自定义Application类中设置默认配置将使其在其余代码中可用。

public class MyApplication extends Application {
  @Override
  public void onCreate() {
    super.onCreate();
    // The default Realm file is "default.realm" in Context.getFilesDir();
    // we'll change it to "myrealm.realm"
    Realm.init(this);
    RealmConfiguration config = new RealmConfiguration.Builder().name("myrealm.realm").build();
    Realm.setDefaultConfiguration(config);
  }
}

public class MyActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Realm realm = Realm.getDefaultInstance(); // opens "myrealm.realm"
    try {
      // ... Do something ...
    } finally {
      realm.close();
    }
  }
}

打开一个同步的Realmhttps://docs.realm.io/platform/icon-default.png?t=L892https://docs.realm.io/platform/只读Realm

只读仅在当前进程中强制执行。其他进程或设备仍然有可能写入只读Realms。另外,针对只读Realm的任何写事务都会抛出IllegalStateException。这包括尝试编写模式,因此最初必须由其他来源提供。
 

在应用程序中附带准备好的Realm文件有时很有用-您可能希望将一些共享数据与应用程序捆绑在一起。在许多情况下,您不想意外修改该Realm,因为数据纯粹是只读的。您可以通过将Realm文件捆绑在资产中并使用readOnly配置来执行此操作:

RealmConfiguration config = new RealmConfiguration.Builder()
    .assetFile("my.realm")
    .readOnly()
    // It is optional, but recommended to create a module that describes the classes
    // found in your bundled file. Otherwise if your app contains other classes
    // than those found in the file, it will crash when opening the Realm as the
    // schema cannot be updated in read-only mode.
    .modules(new BundledRealmModule())
    .build();

内存Realm

通过inMemory配置,您可以创建一个完全在内存中运行而不会持久化到磁盘的领域。

RealmConfiguration myConfig = new RealmConfiguration.Builder()
    .name("myrealm.realm")
    .inMemory()
    .build();

如果内存不足,内存中的Realm可能仍会使用磁盘空间,但是关闭该Realm时,将删除内存中的领域创建的所有文件。不允许使用与持久化Realm相同的名称创建内存中Realm-名称仍然必须唯一。

当所有具有特定名称的内存中Realm实例超出范围而没有引用时,这将释放所有Realm的数据。要使内存Realm在应用程序执行期间始终保持“活跃”状态,请保留对其的引用。


动态Realm

使用常规时Realm,模型类是使用RealmObject子类定义的。关于类型安全性,这有很多好处。但是有时,这些类型直到运行时才可用,例如,在迁移过程中,或使用基于字符串的数据(如CSV文件)时。抢救动态Realms!

一个DynamicRealm是以往的Realm的变种,使得它能够以域数据工作,而无需使用RealmObject子类。而是使用字符串代替类来完成所有访问。

打开动态Realm使用与常规Realm相同的配置,但是动态领域会忽略任何已配置的架构,迁移和架构版本。

RealmConfiguration realmConfig = new RealmConfiguration.Builder().build();
DynamicRealm realm = DynamicRealm.getInstance(realmConfig);

// In a DynamicRealm all objects are DynamicRealmObjects
realm.beginTransaction();
DynamicRealmObject person = realm.createObject("Person");
realm.commitTransaction();

// All fields are accessed using strings
String name = person.getString("name");
int age = person.getInt("age");

// An underlying schema still exists, so accessing a field that does not exist
// will throw an exception
person.getString("I don't exist");

// Queries still work normally
RealmResults<DynamicRealmObject> persons = realm.where("Person")
    .equalTo("name", "John")
    .findAll();

参考: Realm学习笔记_ZPCrobot的博客-CSDN博客

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 是一个快速开发框架,它提供了一系列的工具和插件,可以快速构建一个企业级的应用程序。而 Shiro 是一个强大而灵活的安全框架,可以提供身份验证、授权、密码加密、会话管理等功能。CAS 是一个单点登录(SSO)协议,可以实现用户在多个应用系统中使用同一个身份验证。 下面是一个简单的 Spring Boot + Shiro + CAS 的示例应用程序: 1. 创建一个 Spring Boot 应用程序,并添加依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring-boot-web-starter</artifactId> <version>1.5.3</version> </dependency> <dependency> <groupId>org.jasig.cas.client</groupId> <artifactId>cas-client-core</artifactId> <version>3.6.0</version> </dependency> ``` 2. 配置 Shiro: ```java @Configuration public class ShiroConfig { @Bean public CasRealm casRealm() { CasRealm realm = new CasRealm(); realm.setCasServerUrlPrefix("https://cas.example.com/cas"); realm.setCasService("https://myapp.example.com/cas"); realm.setDefaultRoles("user"); realm.setRoleAttributeNames("memberOf"); return realm; } @Bean public DefaultWebSecurityManager securityManager() { DefaultWebSecurityManager manager = new DefaultWebSecurityManager(); manager.setRealm(casRealm()); return manager; } @Bean public ShiroFilterFactoryBean shiroFilter() { ShiroFilterFactoryBean filter = new ShiroFilterFactoryBean(); filter.setSecurityManager(securityManager()); filter.setLoginUrl("https://cas.example.com/cas/login?service=https://myapp.example.com/cas"); filter.setSuccessUrl("/home"); filter.setUnauthorizedUrl("/403"); filter.setFilterChainDefinitionMap(Collections.singletonMap("/**", "authc")); return filter; } } ``` 3. 配置 CAS: ```java @Configuration public class CasConfig { @Bean public CasAuthenticationFilter casAuthenticationFilter() { CasAuthenticationFilter filter = new CasAuthenticationFilter(); filter.setCasServerLoginUrl("https://cas.example.com/cas/login"); filter.setServerName("https://myapp.example.com/cas"); filter.setAuthenticationSuccessHandler(authenticationSuccessHandler()); filter.setAuthenticationFailureHandler(authenticationFailureHandler()); return filter; } @Bean public SimpleUrlAuthenticationSuccessHandler authenticationSuccessHandler() { SimpleUrlAuthenticationSuccessHandler handler = new SimpleUrlAuthenticationSuccessHandler(); handler.setDefaultTargetUrl("/home"); handler.setAlwaysUseDefaultTargetUrl(true); return handler; } @Bean public SimpleUrlAuthenticationFailureHandler authenticationFailureHandler() { SimpleUrlAuthenticationFailureHandler handler = new SimpleUrlAuthenticationFailureHandler(); handler.setDefaultFailureUrl("/login?error=true"); return handler; } @Bean public FilterRegistrationBean<CasAuthenticationFilter> casFilterRegistrationBean() { FilterRegistrationBean<CasAuthenticationFilter> registration = new FilterRegistrationBean<>(); registration.setFilter(casAuthenticationFilter()); registration.addUrlPatterns("/*"); registration.setName("CAS Authentication Filter"); registration.setOrder(1); return registration; } @Bean public ServletListenerRegistrationBean<SingleSignOutHttpSessionListener> singleSignOutHttpSessionListener() { ServletListenerRegistrationBean<SingleSignOutHttpSessionListener> registration = new ServletListenerRegistrationBean<>(); registration.setListener(new SingleSignOutHttpSessionListener()); registration.setOrder(2); return registration; } @Bean public ServletRegistrationBean<Servlet> casValidationServletRegistrationBean() { ServletRegistrationBean<Servlet> registration = new ServletRegistrationBean<>(); registration.setServlet(new Cas20ProxyReceivingTicketValidationFilter()); registration.addUrlMappings("/cas/*"); registration.setName("CAS Validation Filter"); registration.setOrder(3); return registration; } } ``` 4. 创建一个 HomeController: ```java @Controller public class HomeController { @GetMapping("/home") public String home() { return "home"; } @GetMapping("/403") public String error403() { return "403"; } } ``` 5. 创建一个 CAS 认证服务器: ```java @SpringBootApplication public class CasServerApplication { public static void main(String[] args) { SpringApplication.run(CasServerApplication.class, args); } } ``` 6. 创建一个 CAS 客户端: ```java @SpringBootApplication @EnableScheduling public class CasClientApplication { public static void main(String[] args) { SpringApplication.run(CasClientApplication.class, args); } } ``` 这就是一个简单的 Spring Boot + Shiro + CAS 的示例应用程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值