Java是企业级应用开发中非常流行的编程语言,而Java框架则是帮助开发者快速构建高效、可靠应用的工具。本文将介绍Java开发中常用的四大框架:Spring、Hibernate、Struts和MyBatis,并提供相关代码示例。
1. Spring框架
Spring是一个功能强大的开源框架,广泛用于构建企业级应用。它提供了全面的基础架构支持,尤其是其依赖注入(DI)和面向切面编程(AOP)功能。
1.1 依赖注入示例
依赖注入是Spring的核心功能之一。下面是一个简单的示例:
配置文件(applicationContext.xml)
xml
复制代码
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="myService" class="com.example.MyService"/>
<bean id="myApp" class="com.example.MyApp">
<property name="service" ref="myService"/>
</bean>
</beans>
Java代码
java
复制代码
package com.example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyApp {
private MyService service;
public void setService(MyService service) {
this.service = service;
vxhao888.cn/fjava5I/
public void run() {
service.perform();
}
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
MyApp app = (MyApp) context.getBean("myApp");
app.run();
}
}
class MyService {
public void perform() {
System.out.println("Service is performing...");
}
}
2. Hibernate框架
Hibernate是一个开源的对象关系映射(ORM)框架,用于将Java对象映射到数据库表。它极大地简化了数据库操作。
2.1 基本CRUD操作示例
以下是使用Hibernate进行基本CRUD操作的示例:
配置文件(hibernate.cfg.xml)
xml
复制代码
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<mapping class="com.example.User"/>
</session-factory>
</hibernate-configuration>
实体类(User.java)
java
复制代码
package com.example;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class User {
@Id
private int id;
private String name;
// Getters and setters
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
CRUD操作
java
复制代码
package com.example;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Main {
public static void main(String[] args) {
SessionFactory factory = new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
session.beginTransaction();
// Create
User user = new User();
user.setId(1);
user.setName("John Doe");
session.save(user);
// Read
User retrievedUser = session.get(User.class, 1);
System.out.println(retrievedUser.getName());
// Update
retrievedUser.setName("Jane Doe");
session.update(retrievedUser);
// Delete
session.delete(retrievedUser);
session.getTransaction().commit();
session.close();
}
}
3. Struts框架
Struts是一个基于MVC设计模式的Web应用框架,它简化了Java EE Web应用的开发过程。
3.1 基本示例
配置文件(struts-config.xml)
xml
复制代码
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<form-beans>
<form-bean name="userForm" type="com.example.UserForm"/>
</form-beans>
<action-mappings>
<action path="/login" type="com.example.LoginAction"
name="userForm" scope="request" validate="true"
input="/login.jsp">
<forward name="success" path="/welcome.jsp"/>
<forward name="failure" path="/login.jsp"/>
</action>
</action-mappings>
</struts-config>
Java代码
java
复制代码
package com.example;
bdhyr.com/java9w/
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class LoginAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
UserForm userForm = (UserForm) form;
if ("admin".equals(userForm.getUsername()) && "password".equals(userForm.getPassword())) {
return mapping.findForward("success");
} else {
return mapping.findForward("failure");
}
}
}
class UserForm extends ActionForm {
private String username;
private String password;
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
}
4. MyBatis框架
MyBatis是一款优秀的持久层框架,它简化了JDBC和数据库操作,使开发者可以专注于SQL本身。
4.1 基本示例
配置文件(mybatis-config.xml)
xml
复制代码
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/example/UserMapper.xml"/>
</mappers>
</configuration>
映射文件(UserMapper.xml)
xml
复制代码
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.UserMapper">
<select id="selectUser" parameterType="int" resultType="com.example.User">
SELECT * FROM users WHERE id = #{id}
hzojz.com/javaC9/
<insert id="insertUser" parameterType="com.example.User">
INSERT INTO users (id, name) VALUES (#{id}, #{name})
</insert>
<update id="updateUser" parameterType="com.example.User">
UPDATE users SET name = #{name} WHERE id = #{id}
</update>
<delete id="deleteUser" parameterType="int">
DELETE FROM users WHERE id = #{id}
</delete>
</mapper>
Java代码
java
复制代码
package com.example;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class Main {
public static void main(String[] args) throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession session = sqlSessionFactory.openSession()) {
UserMapper mapper = session.getMapper(UserMapper.class);
// Create
User newUser = new User();
newUser.setId(1);
newUser.setName("John Doe");
mapper.insertUser(newUser);
session.commit();
// Read
User user = mapper.selectUser(1);
System.out.println(user.getName());