- 导入依赖:新建一个maven的project,导入如下依赖:
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
</dependencies>
#驱动加载
driverClassName=com.mysql.jdbc.Driver
#注册驱动
url=jdbc:mysql://127.0.0.1:3306/yourDbName?characterEncoding=utf-8&useSSL=false
#连接数据库的用户名
username=root
#连接数据库的密码
password=yourPassword
#属性类型的字符串,通过别名的方式配置扩展插件, 监控统计用的stat 日志用log4j 防御sql注入:wall
filters=stat
#初始化时池中建立的物理连接个数。
initialSize=2
#最大的可活跃的连接池数量
maxActive=300
#获取连接时最大等待时间,单位毫秒,超过连接就会失效。配置了maxWait之后,缺省启用公平锁,并发效率会有所下降, 如果需要可以通过配置useUnfairLock属性为true使用非公平锁。
maxWait=60000
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TableName {
String value();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TableColumn {
String value();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TableColumn {
String value();
}
- 创建需要操作的实体类:以user表为例
@AllArgsConstructor
@NoArgsConstructor
@Data
@TableName("user")
public class User implements Serializable {
@TableId(value = "id")
private Integer id;
private String username;
private String password;
private Integer tel;
private String email;
public User(Integer id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
}
public class ConnFactory {
private static DataSource dataSource;
static {
try {
InputStream in = ConnFactory.class.getClassLoader().getResourceAsStream("druid.properties");
Properties properties = new Properties();
properties.load(in);
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
}
public static Connection getConn(){
Connection connection = null;
try {
connection = dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public static void close(ResultSet set, PreparedStatement ps,Connection conn){
try{
if(set!=null){
set.close();
}
} catch (Exception e){
e.printStackTrace();
}
try{
if(ps!=null){
ps.close();
}
} catch (Exception e){
e.printStackTrace();
}try{
if(conn!=null){
conn.close();
}
} catch (Exception e){
e.printStackTrace();
}
}
}
public class DateFormat {
public static String format(Date date){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
return simpleDateFormat.format(date);
}
}
public class BaseDao<T> {
private Class cls;
public BaseDao(){
Class<? extends BaseDao> aClass = this.getClass();
ParameterizedType type = (ParameterizedType) aClass.getGenericSuperclass();
Type[] actualTypeArguments = type.getActualTypeArguments();
this.cls = (Class) actualTypeArguments[0];
}
public T selectAnyOneByPrimary(Integer id){
Connection conn = ConnFactory.getConn();
StringBuilder stringBuilder = new StringBuilder("select ");
Field[] declaredFields = cls.getDeclaredFields();
ArrayList<String> fieldNames = new ArrayList<>();
for (Field field: declaredFields) {
field.setAccessible(true);
TableId tableIdAnnotation = field.getAnnotation(TableId.class);
TableColumn tableColumnAnnotation = field.getAnnotation(TableColumn.class);
if(tableIdAnnotation != null){
fieldNames.add(tableIdAnnotation.value());
}else if(tableColumnAnnotation != null){
fieldNames.add(tableColumnAnnotation.value());
}else {
fieldNames.add(field.getName());
}
}
String columnNames = fieldNames.toString().replace("[","").replace("]"," from");
stringBuilder.append(columnNames+" ");
TableName tableNameAnnotation = (TableName) cls.getAnnotation(TableName.class);
String tableName = "";
if(tableNameAnnotation != null){
tableName = tableNameAnnotation.value();
}else{
tableName = cls.getSimpleName();
}
stringBuilder.append(tableName+" where ");
String primaryKey = "";
for(Field field:declaredFields){
field.setAccessible(true);
TableId tableIdAnnotation = field.getAnnotation(TableId.class);
if(tableIdAnnotation != null){
primaryKey = tableIdAnnotation.value();
break;
}
}
stringBuilder.append(primaryKey+" = ?");
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
preparedStatement = conn.prepareStatement(String.valueOf(stringBuilder));
preparedStatement.setInt(1,id);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
Object o = cls.newInstance();
for (Field field: declaredFields) {
field.setAccessible(true);
TableId tableIdAnnotation = field.getAnnotation(TableId.class);
TableColumn tableColumnAnnotation = field.getAnnotation(TableColumn.class);
if(tableIdAnnotation != null){
field.set(o,resultSet.getObject(tableIdAnnotation.value()));
}else if(tableColumnAnnotation != null){
field.set(o,resultSet.getObject(tableColumnAnnotation.value()));
}else{
field.set(o,resultSet.getObject(field.getName()));
}
}
if(o != null){
return (T) o;
}else{
return null;
}
}
} catch (SQLException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return null;
}
public List<T> selectList(Integer currentPage,Integer pageSize){
Connection conn = ConnFactory.getConn();
StringBuilder stringBuilder = new StringBuilder("select ");
Field[] declaredFields = cls.getDeclaredFields();
ArrayList<String> fieldNames = new ArrayList<>();
for (Field field: declaredFields) {
field.setAccessible(true);
TableId tableIdAnnotation = field.getAnnotation(TableId.class);
TableColumn tableColumnAnnotation = field.getAnnotation(TableColumn.class);
if(tableIdAnnotation != null){
fieldNames.add(tableIdAnnotation.value());
}else if(tableColumnAnnotation != null){
fieldNames.add(tableColumnAnnotation.value());
}else {
fieldNames.add(field.getName());
}
}
String columnNames = fieldNames.toString().replace("[","").replace("]"," from");
stringBuilder.append(columnNames+" ");
TableName tableNameAnnotation = (TableName) cls.getAnnotation(TableName.class);
String tableName = "";
if(tableNameAnnotation != null){
tableName = tableNameAnnotation.value();
}else{
tableName = cls.getSimpleName();
}
stringBuilder.append(tableName+" limit ?,? ");
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
ArrayList<T> list = new ArrayList<>();
try {
preparedStatement = conn.prepareStatement(String.valueOf(stringBuilder));
preparedStatement.setObject(1,currentPage);
preparedStatement.setObject(2,pageSize);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
Object o = cls.newInstance();
for (Field field: declaredFields) {
field.setAccessible(true);
TableId tableIdAnnotation = field.getAnnotation(TableId.class);
TableColumn tableColumnAnnotation = field.getAnnotation(TableColumn.class);
if(tableIdAnnotation != null){
field.set(o,resultSet.getObject(tableIdAnnotation.value()));
}else if(tableColumnAnnotation != null){
field.set(o,resultSet.getObject(tableColumnAnnotation.value()));
}else{
field.set(o,resultSet.getObject(field.getName()));
}
}
list.add((T) o);
}
return list;
} catch (SQLException e) {
e.printStackTrace();
}catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}finally {
ConnFactory.close(resultSet,preparedStatement,conn);
}
return null;
}
public int insert(T t){
Connection conn = ConnFactory.getConn();
StringBuilder stringBuilder = new StringBuilder("insert into ");
Class<?> aClass = t.getClass();
TableName tableNameAnnotation = aClass.getAnnotation(TableName.class);
String tableName = "";
if(tableNameAnnotation != null){
tableName = tableNameAnnotation.value();
}else{
tableName = aClass.getSimpleName();
}
stringBuilder.append(tableName);
Field[] declaredFields = aClass.getDeclaredFields();
ArrayList<String> fieldNames = new ArrayList<>();
for (Field field: declaredFields) {
field.setAccessible(true);
TableId tableIdAnnotation = field.getAnnotation(TableId.class);
TableColumn tableColumnAnnotation = field.getAnnotation(TableColumn.class);
if(tableIdAnnotation != null){
fieldNames.add(tableIdAnnotation.value());
}else if(tableColumnAnnotation != null){
fieldNames.add(tableColumnAnnotation.value());
}else {
fieldNames.add(field.getName());
}
}
String columnNames = fieldNames.toString().replace("[","(").replace("]",")" + "values");
stringBuilder.append(columnNames);
ArrayList<Object> placeholderList = new ArrayList<>();
ArrayList<Object> columnValues = new ArrayList<>();
for (Field field: declaredFields) {
field.setAccessible(true);
try {
if(field.get(t) instanceof String){
columnValues.add(field.get(t).toString());
}else if(field.get(t) instanceof Date){
String format = DateFormat.format((Date) field.get(t));
columnValues.add(format);
}else{
columnValues.add(field.get(t));
}
placeholderList.add("?");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
String str = placeholderList.toString().replace("[","(").replace("]",")");
stringBuilder.append(str);
PreparedStatement preparedStatement = null;
try {
preparedStatement = conn.prepareStatement(String.valueOf(stringBuilder));
for (int i = 0; i < columnValues.size(); i++) {
preparedStatement.setObject(i+1,columnValues.get(i));
}
int i = preparedStatement.executeUpdate();
if(i > 0){
return i;
}else{
return 0;
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
ConnFactory.close(null,preparedStatement,conn);
}
return 0;
}
public int update(T t){
Connection conn = ConnFactory.getConn();
StringBuilder stringBuilder = new StringBuilder("update ");
TableName tableNameAnnotation = (TableName) cls.getAnnotation(TableName.class);
String tableName = "";
if(tableNameAnnotation != null){
tableName = tableNameAnnotation.value();
}else {
tableName = cls.getSimpleName();
}
stringBuilder.append(tableName+" set ");
Field[] declaredFields = cls.getDeclaredFields();
ArrayList<Object> list = new ArrayList<>();
for (int i = 0; i <declaredFields.length; i++) {
declaredFields[i].setAccessible(true);
try {
if(i == declaredFields.length -1 ){
stringBuilder.append(declaredFields[i].getName()+" = ?");
}else{
stringBuilder.append(declaredFields[i].getName()+" = ?,");
}
list.add(declaredFields[i].get(t));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
stringBuilder.append(" where ");
Object primaryKey = null;
Object primaryKeyValue = null;
for(Field field:declaredFields) {
field.setAccessible(true);
TableId tableIdAnnotation = field.getAnnotation(TableId.class);
if (tableIdAnnotation != null) {
try {
primaryKeyValue = field.get(t);
primaryKey = tableIdAnnotation.value();
stringBuilder.append(primaryKey + " = ?" );
break;
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
PreparedStatement preparedStatement = null;
try {
preparedStatement = conn.prepareStatement(String.valueOf(stringBuilder));
for (int i = 0; i < list.size(); i++) {
preparedStatement.setObject(i+1,list.get(i));
}
preparedStatement.setObject(list.size()+1,primaryKeyValue);
int i = preparedStatement.executeUpdate();
if(i > 0){
return i;
}else{
return 0;
}
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
public int delete(Integer id){
Connection conn = ConnFactory.getConn();
StringBuilder stringBuilder = new StringBuilder("delete from ");
TableName tableNameAnnotation = (TableName) cls.getAnnotation(TableName.class);
String tableName = "";
if(tableNameAnnotation != null){
tableName = tableNameAnnotation.value();
}else {
tableName = cls.getSimpleName();
}
stringBuilder.append(tableName+" where ");
Field[] declaredFields = cls.getDeclaredFields();
String primaryKey = "";
for(Field field:declaredFields){
field.setAccessible(true);
TableId tableIdAnnotation = field.getAnnotation(TableId.class);
if(tableIdAnnotation != null){
primaryKey = tableIdAnnotation.value();
break;
}
}
stringBuilder.append(primaryKey+" = ? ");
PreparedStatement preparedStatement = null;
try {
preparedStatement = conn.prepareStatement(String.valueOf(stringBuilder));
preparedStatement.setObject(1,id);
int i = preparedStatement.executeUpdate();
if(i > 0){
return i;
}else{
return 0;
}
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
}
public class UserDao extends BaseDao<User> {
}
public class MyOrmTest {
public static void main(String[] args) {
UserDao userDao = new UserDao();
int insert = userDao.insert(new User(null, "11111","1111"));
System.out.println("新增了"+insert);
List<User> users = userDao.selectList(1,2);
System.out.println("user分页查询的列表是"+users);
int delete = userDao.delete(8);
System.out.println("删除了嘛"+delete);
User user = userDao.selectAnyOneByPrimary(12);
System.out.println("根据主键查询的user对象是"+user);
int update = userDao.update(new User(10, "123456", "123456"));
System.out.println("修改成功了吗"+update);
}
}
- 测试结果:含拼接后的sql语句打印
- 可选:打成jar包供小伙伴使用(虽然很lj,但也是自己的一番心血不是)
再不济总能在外行面前装个
- 完结撒花