【JPA】开始
Java SE中使用
实体Bean
package cn.ycx.entity; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Employee { @Id private int id; private String name; private long salary; 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; } public long getSalary() { return salary; } public void setSalary(long salary) { this.salary = salary; } @Override public String toString() { return "Employee [id=" + id + ", name=" + name + ", salary=" + salary + "]"; } }
服务
package cn.ycx.service; import javax.persistence.EntityManager; import cn.ycx.entity.Employee; public class EmployeeService { private EntityManager em; public EmployeeService (EntityManager em) { this.em = em; } public Employee createEmployee(int id, String name, long salary) { Employee employee = new Employee(); employee.setId(id); employee.setName(name); employee.setSalary(salary); em.persist(employee); return employee; } }
测试
package cn.ycx.test; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import cn.ycx.entity.Employee; import cn.ycx.service.EmployeeService; public class EmployeeTest { public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("EmployeeServiceUnit"); EntityManager em = emf.createEntityManager(); EmployeeService service = new EmployeeService(em); EntityTransaction et = em.getTransaction(); et.begin(); Employee employee = service.createEmployee(1, "tom", 5000); et.commit(); System.out.println(employee); } }
配置
<?xml version="1.0" encoding="UTF-8"?> <persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> <persistence-unit name="EmployeeServiceUnit" transaction-type="RESOURCE_LOCAL"> <class>cn.ycx.entity.Employee</class> <properties> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/ycxfw"/> <property name="javax.persistence.jdbc.user" value="root"/> <property name="javax.persistence.jdbc.password" value="123456"/> </properties> </persistence-unit> </persistence>
分类:
JPA
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南