ORM框架: O(Object 对象)R(Relative关系)M(Mapping映射)对象关系映射。把数据中的表映射为java中的实体类,表中的一条记录映射为java实体类对象。表中的列映射为实体类的属性。
使用技术: 泛型,注解,反射。
创建一个maven工程并引入相关依赖
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.31</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.26</version>
</dependency>
</dependencies>
创建一个连接数据库的工具类
在resources下创建db.properties
db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
db.username=******
db.password=******
在utils下创建DbUtils
public class DbUtils {
//硬编码
private static String driver = "";
private static String url = "";
private static String username = "";
private static String password = "";
static {
try {
//静态代码块,随着类的加载而加载,且只会被加载一次
InputStream inputStream = ClassLoader.getSystemResourceAsStream("db.properties");
Properties properties = new Properties();
//加载属性文件
properties.load(inputStream);
driver = properties.getProperty("db.driver");
url = properties.getProperty("db.url");
username = properties.getProperty("db.username");
password = properties.getProperty("db.password");
} catch (IOException e) {
System.out.println("名为db.properties的属性文件不存在");
throw new RuntimeException(e);
}
}
/*运行后得到com.mysql.cj.jdbc.ConnectionImpl@480bdb19,表示此类完成*/
public static void main(String[] args) throws Exception {
System.out.println(getConnection());
}
//获取连接对象
public static Connection getConnection() throws SQLException, ClassNotFoundException {
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
//关闭资源
public static void closeAll(Connection connection, PreparedStatement ps, ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}