IDEA 全称 IntelliJ IDEA,是java编程语言开发的集成环境。IntelliJ在业界被公认为最好的java开发工具,尤其在智能代码助手、代码自动提示、重构、JavaEE支持、各类版本工具(git、svn等)、JUnit、CVS整合、代码分析、 创新的GUI设计等方面的功能可以说是超常的。
Maven 是一款基于 Java 平台的项目管理和整合工具,它将项目的开发和管理过程抽象成一个项目对象模型(POM)。开发人员只需要做一些简单的配置,Maven 就可以自动完成项目的编译、测试、打包、发布以及部署等工作。
OS:macOS High Sierra (Version: 10.13.6)
IDEA:IntelliJ IDEA 2020.1.4 (Community Edition)
Database: MariaDB 10.1.13 (MariaDB是MySQL源代码的一个分支)
1. 安装 Java 8+
$ java -version
openjdk version "1.8.0_302"
OpenJDK Runtime Environment Corretto-8.302.08.1 (build 1.8.0_302-b08)
OpenJDK 64-Bit Server VM Corretto-8.302.08.1 (build 25.302-b08, mixed mode)
2. 安装 Maven 3.8.1
https://maven.apache.org/
$ wget https://mirrors.bfsu.edu.cn/apache/maven/maven-3/3.8.1/binaries/apache-maven-3.8.1-bin.tar.gz
$ mv ./apache-maven-3.8.1-bin.tar.gz ~/Applications/java/ # 移动到你想要放置的文件夹
$ tar -zvxf apache-maven-3.8.1-bin.tar.gz # ~/Applications/java/apache-maven-3.8.1
$ sudo vim /etc/profile
# Add JAVA_HOME ...
JAVA_HOME=/Users/xxx/Library/Java/JavaVirtualMachines/corretto-1.8.0_302/Contents/Home
JRE_HOME=$JAVA_HOME/jre
CLASS_PATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar:$JRE_HOME/lib
PATH=$PATH:$JAVA_HOME/bin:$JRE_HOME/bin:/Users/xxx/Applications/java/apache-maven-3.8.1/bin
export JAVA_HOME JRE_HOME CLASS_PATH PATH
$ source /etc/profile
$ vim ~/Applications/java/apache-maven-3.8.1/conf/settings.xml
...
# 修改本地仓库路径
...
# 修改成阿里源
3. 安装 IntelliJ Idea
下载 https://www.jetbrains.com/idea/download/download-thanks.html?platform=mac&code=IIC
Mac OS: ideaIC-2020.1.dmg
Windows: ideaIC-2020.1.exe
运行 Idea 并配置:
IntelliJ IDEA -> Preferences -> Build, Execution, Deployment -> Build Tools -> Maven
Maven home path: ~/Applications/java/apache-maven-3.8.1
User settings file: ~/Applications/java/apache-maven-3.8.1/conf/settings.xml
Local repository: ~/Applications/java/maven-repository
4. 在 IDEA上创建 Maven 项目
New Project -> Project Type: Maven -> Project SDK: 1.8 -> select maven-archtype-quickstart: Next
Name: MavenQuickstart
GroupId: com.example
ArtifactId: MavenQuickstart
-> Finish
1) 生成的项目目录结构
|-- src
| |-- main
| | |-- java
| | |-- com
| | |-- example
| | |-- App.java
| |-- test
| |-- java
| |-- com
| |-- example
| |-- AppTest.java
|-- pom.xml
2) App.java
package com.example;
public class App {
public static void main( String[] args ) {
System.out.println( "Hello World!" );
}
}
5. 编译和运行
在IDE中项目列表 External Libraries -> <1.x> -> Open Library Settings -> Platform Settings -> SDKS
Name: 1.8
JDK home path: select 1.8 SDK or download a SDK
1) Run App.main()
Open App.java, click mouse right button, select Run "App.main()"
2) Edit Configurations
Click "+" add new configuration -> Select "Application"
Name: MaventQuickstart
Main class: com.example.App
-> Apply / OK
Click Run "MavenQuickstart"
6. 导入 MariaDB, log4j (非必选)
访问 http://www.mvnrepository.com/,查询 MariaDB, log4j
修改 pom.xml
...
...
...
...
在IDE中项目列表 -> 点击鼠标右键 -> Maven -> Reload Project
7. 支持 log4j (非必选)
添加 src/main/resources/log4j.properties
# Define the root logger with appender file
log4j.rootLogger = DEBUG, FILE
# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
# Set the name of the file
log4j.appender.FILE.File=/Users/xxx/logs/maven-quickstart_log4j.txt
# Set the immediate flush to true (default)
log4j.appender.FILE.ImmediateFlush=true
# Set the threshold to debug mode
log4j.appender.FILE.Threshold=debug
# Set the append to false, overwrite
log4j.appender.FILE.Append=false
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
8. 数据库和表
1) MySQL/MariaDB
Database Name: testdb
User: root
Password: 123456
SQL:
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`password` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`createtime` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2) Add src/main/resources/config.properties
# Database Config
db_driverClassName=org.mariadb.jdbc.Driver
db_url=jdbc:mysql://localhost/testdb?characterEncoding=utf8
db_username=root
db_password=123456
3) 添加 src/main/java/com/example/entity/User.java
package com.example.entity;
import java.text.SimpleDateFormat;
import java.util.Date;
public class User {
private int id;
private String name;
private String password;
private int age;
private Date createtime;
public User() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
public Date getCreatetime() {
return this.createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
@Override
public String toString() {
String strCreateTime = "";
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if (createtime != null)
strCreateTime = f.format(createtime);
return "id: " + id + ", name: " + name + ", age: " + age + ", createtime: " + strCreateTime;
}
}
4) 添加 src/main/java/com/example/DemoJDBC.java
package com.example;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.example.App;
public class DemoJdbc {
private String strName = "jdbcUser";
private String strConfig = "/config.properties";
public void runDB() {
App.log.info("DemoJdbc -> runDB()");
try {
// Read config file
InputStream resStream = this.getClass().getResourceAsStream(strConfig);
Properties properties = new Properties();
properties.load(resStream);
String strDriverName = properties.getProperty("db_driverClassName");
String strUrl = properties.getProperty("db_url");
String strUsername = properties.getProperty("db_username");
String strPassword = properties.getProperty("db_password");
System.out.println("db_driverClassName: " + strDriverName);
//
System.out.println("Connecting to MariaDB ...");
Class.forName(strDriverName);
Connection conn = DriverManager.getConnection(strUrl, strUsername, strPassword);
String strSql = "SELECT * FROM user WHERE name = ?";
PreparedStatement ps = conn.prepareStatement(strSql);
ps.setString(1, strName);
ResultSet rs = ps.executeQuery();
if(rs.next()) {
System.out.println("Name = " + rs.getString("name"));
} else {
strSql = "INSERT INTO user (name, password, age, createtime) values (?, ?, ?, ?)";
PreparedStatement ps2 = conn.prepareStatement(strSql);
ps2.setString(1, strName);
ps2.setString(2, "123456");
ps2.setInt(3, 25);
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ps2.setString(4, f.format(new Date()));
int ret = ps2.executeUpdate();
if (ret > 0) {
System.out.println("Add '" + strName + "' to database successfully, ret = " + ret);
} else {
System.out.println("Add '" + strName + "' to database failed, ret = " + ret);
}
}
} catch (ClassNotFoundException err) {
err.printStackTrace();
} catch (SQLException err2) {
err2.printStackTrace();
} catch (IOException err3) {
err3.printStackTrace();
} catch (Exception err4) {
err4.printStackTrace();
}
}
}
5) 修改 src/main/java/com/example/App.java
package com.example;
import org.apache.log4j.Logger
public class App {
public static Logger log = Logger.getLogger(App.class.getName());
public static void main(String[] args) throws Exception {
DemoJdbc demoJdbc = new DemoJdbc();
demoJdbc.runDB();
}
}
运行步骤 5, 编译和运行
9. 打包 jar
以下三种打包方法独立使用,pom.xml 里同一时间只存在一种方式。
1) 使用 maven-jar-plugin 和 maven-dependency-plugin 插件打包
添加/修改 pom.xml 的 build 部分:
在IDE中项目列表 -> 点击鼠标右键 -> Maven -> Reload Project
View -> Tool Windows -> Maven -> MavenQuickstart -> Lifecycle -> Clean | Package
Idea -> Terminal
$ java -jar target/MavenQuickstart-1.0-SNAPSHOT.jar
Connecting to MariaDB ...
...
*注:MavenQuickstart-1.0-SNAPSHOT.jar 里不包含依赖的包,依赖包在 target/lib 目录下
2)使用 maven-assembly-plugin 插件打包
添加/修改 pom.xml 的 build 部分:
在IDE中项目列表 -> 点击鼠标右键 -> Maven -> Reload Project
View -> Tool Windows -> Maven -> MavenQuickstart -> Lifecycle -> Clean | Package
Idea -> Terminal
$ java -jar target/MavenQuickstart-1.0-SNAPSHOT-jar-with-dependencies.jar
Connecting to MariaDB ...
...
*注:MavenQuickstart-1.0-SNAPSHOT.jar 里不包含依赖的包(要手动配置依赖环境),MavenQuickstart-1.0-SNAPSHOT-jar-with-dependencies.jar 包含依赖包,可以直接运行。 如果项目中用到spring Framework,用这种方式打出来的包运行时可能会出错。
3)使用 maven-shade-plugin 插件打包
项目中用到 spring Framework, 使用这种打包方式。
添加/修改 pom.xml 的 build 部分:
在IDE中项目列表 -> 点击鼠标右键 -> Maven -> Reload Project
View -> Tool Windows -> Maven -> MavenQuickstart -> Lifecycle -> Clean | Package
Idea -> Terminal
$ java -jar target/MavenQuickstart-1.0-SNAPSHOT.jar
Connecting to MariaDB ...
...
*注: original-MavenQuickstart-1.0-SNAPSHOT.jar 里不包含依赖的包(要手动配置依赖环境),MavenQuickstart-1.0-SNAPSHOT.jar 包含依赖包,可以直接运行。