IDE
起步,创建一个 Maven 项目,在 pom.xml 中配置如下
<build>
<plugins>
<plugin>
<groupId>com.speedment</groupId>
<artifactId>speedment-maven-plugin</artifactId>
<version>3.0.18</version>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.speedment</groupId>
<artifactId>runtime</artifactId>
<version>3.0.18</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
<scope>runtime</scope>
</dependency>
</dependencies>
Speedment UI
Speedment 提供了一个 Maven 插件,你可以用它连接数据库,并通过配置,生成项目代码。
-
通过命令或者 IDE 运行插件
mvn speedment:tool
-
加入社区
-
连接数据库
-
生成 Java 代码
-
完成
Hello Speedment
hello world 项目,写一个小程序,将输入的用户姓名、年龄持久化到 MySql 中。
-
准备数据库
CREATE DATABASE hellospeedment; USE hellospeedment; CREATE TABLE IF NOT EXISTS `user` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(32) NOT NULL, `age` int(5) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
-
通过插件生成代码
generated
包中为自动生成的Application
相关。hellospeedment.hellospeedment.user
包为对应数据库、表生成的实体相关。 -
初始化 Speedment ,写一个主类如下
public class Main { public static void main(String[] args) { // 创建一个 application 实例,指定数据库密码及日志 HellospeedmentApplication app = new HellospeedmentApplicationBuilder() .withPassword("123456") .withLogging(PERSIST) .build(); // 创建 entity manager 实例 UserManager users = app.getOrThrow(UserManager.class); // 创建控制台 Scanner final Scanner scn = new Scanner(System.in); // 接收输入参数 System.out.print("What is your name? "); final String name = scn.nextLine(); System.out.print("What is your age? "); final int age = scn.nextInt(); try { User user = new UserImpl() .setName(name) .setAge(age); // 持久化到数据库 user = users.persist(user); System.out.print("Hello, " + user.getName() + "!"); } catch (SpeedmentException se) { System.out.print("Why are you so persistent?"); se.printStackTrace(); } } }
运行结果如下
What is your name? Gnar What is your age? 3 2017-11-18T08:18:18.760Z DEBUG [main] (#PERSIST) - INSERT INTO `hellospeedment`.`user` (`id`,`name`,`age`) VALUES (?,?,?), values:[0, Gnar, 3] Hello, Gnar!
HellospeedmentApplication
是由 Speedment 自动生成的,从名称上看,这个实例代表应用程序。它负责处理与数据库的连接,并进行 所有的初始化操作。GeneratedUser
接口定义了实体的数据库属性,及Setter
,Getter
方法。GeneratedUserImpl
中实现了Setter
和Getter
,相当于是一个 Java bean。UserManager
是实体的管理者,它实现了Manager
接口,后者定义了一些 CRUD 的(默认)方法,以及 Stream 对象。UserImpl
是实体的最终实现,一些业务逻辑写到这里面。