admin管理员组

文章数量:1616416

Springdata Jpa

Java持久化API,是Sun官方在JDK5.0后提出的Java持久化规范(JSR 338,这些接口所在包为javax.persistence,详细内容可参考https://github/javaee/jpa-spec)
JPA的出现主要是为了简化持久层开发以及整合ORM技术,结束Hibernate、TopLink、JDO等ORM框架各自为营的局面。JPA是在吸收现有ORM框架的基础上发展而来,易于使用,伸缩性强

作者:fulgens
链接:https://www.jianshu/p/c23c82a8fcfc
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

创建文件

重要代码

package com.zhongruan.news.entity;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Entity
@Table(name = "t_user")
public class User {
    @Id
    @GeneratedValue
    private Long id;
    private String nickname;    // 昵称
    private String username;    // 用户名
    private String password;    // 密码
    private String email;       // 邮箱
    private String avatar;      // 头像的url
    private Integer type;       // 用户激活状态
    // 由于数据库不能存储java对象  所用通过@Temporal 注解 Date对象转换成 时间戳 存储到数据库中
    @Temporal(TemporalType.TIMESTAMP)
    private Date createTime;    // 用户创建时间

    @Temporal(TemporalType.TIMESTAMP)
    private Date updateTime;    // 用户的更新时间

    @OneToMany(mappedBy = "user")
    private List<News> newsList = new ArrayList<>();    // 新闻

    public User() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    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;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getAvatar() {
        return avatar;
    }

    public void setAvatar(String avatar) {
        this.avatar = avatar;
    }

    public Integer getType() {
        return type;
    }

    public void setType(Integer type) {
        this.type = type;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }


    public List<News> getNewsList() {
        return newsList;
    }

    public void setNewsList(List<News> newsList) {
        this.newsList = newsList;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", nickname='" + nickname + '\'' +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                ", avatar='" + avatar + '\'' +
                ", type=" + type +
                ", createTime=" + createTime +
                ", updateTime=" + updateTime +
                '}';
    }
}

spring:
  thymeleaf:
    mode: HTML5
  # 配置数据源
  datasource:
    url: jdbc:mysql://localhost:3306/whlg01?serverTimezone=Asia/Shanghai&characterEnconding=utf-8
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: password
  # JPA 的配置
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
# 指定端口
server:
  port: 8090
# 指定日志
logging:
  level:
    root: info
  file:
    path: log/blog
package com.zhongruan.news.aspects;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;


@Aspect
@Component
public class LogAspect {
    // 日志记录器
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /*
        @Aspect 表示该类是一个切面类
    */

    @Pointcut("execution(* com.zhongruan.news.web.*.*(..))")
    public void log() {
        /*
            execution(* com.zhongruan.web.*.*(..))
                * 修饰符
        */
    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        System.out.println("-----------doBefore----------");
        // 将 用户访问的url  ip  调用的方法  传递的参数
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        RequestLog requestLog = new RequestLog(url, ip, classMethod, args);
        logger.info("Result: {}", requestLog);
    }

    @After("log()")
    public void doAfter() {
        System.out.println("-----------doAfter----------");
    }

    @AfterReturning(returning = "result", pointcut = "log()")
    public void doAfterReturn(Object result) {
        logger.info("Result:{}", result);
    }

    private class RequestLog {
        private String url;
        private String ip;
        private String classMethod;
        private Object[] args;

        public RequestLog() {
        }

        public RequestLog(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getIp() {
            return ip;
        }

        public void setIp(String ip) {
            this.ip = ip;
        }

        public String getClassMethod() {
            return classMethod;
        }

        public void setClassMethod(String classMethod) {
            this.classMethod = classMethod;
        }

        public Object[] getArgs() {
            return args;
        }

        public void setArgs(Object[] args) {
            this.args = args;
        }

        @Override
        public String toString() {
            return "RequestLog{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }

}

package com.zhongruan.news.entity;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Entity
@Table(name = "t_news")
public class News {

    @Id
    @GeneratedValue
    private Long id;

    private String title;           // 新闻标题
    private String content;         // 新闻内容
    private String firstPicture;    // 新闻图片的url
    private String flag;            // 新闻状态
    private Integer views;          // 新闻的浏览次数
    private boolean appreciation;   // 新闻的赞赏功能
    private boolean shareStatement; // 新闻的转载许可
    private boolean commentabled;   // 新闻的评论许可
    private boolean published;      // 新闻的发布
    private boolean recommend;      // 新闻是否推荐

    @Temporal(TemporalType.TIMESTAMP)
    private Date createTime;        // 新闻创建时间
    @Temporal(TemporalType.TIMESTAMP)
    private Date updateTime;        // 新闻的更新时间

    @ManyToOne
    private Type type;              // 新闻的类型

    @ManyToMany(cascade = {CascadeType.PERSIST})
    private List<Tag> tags = new ArrayList<>(); // 新闻的标签

    @ManyToOne
    private User user;              // 新闻的作者

    @OneToMany(mappedBy = "news")
    private List<Comment> comments = new ArrayList<>();  // 新闻的评论

    @Transient
    private String tagIds;

    private String description;

    public News() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getFirstPicture() {
        return firstPicture;
    }

    public void setFirstPicture(String firstPicture) {
        this.firstPicture = firstPicture;
    }

    public String getFlag() {
        return flag;
    }

    public void setFlag(String flag) {
        this.flag = flag;
    }

    public Integer getViews() {
        return views;
    }

    public void setViews(Integer views) {
        this.views = views;
    }

    public boolean isAppreciation() {
        return appreciation;
    }

    public void setAppreciation(boolean appreciation) {
        this.appreciation = appreciation;
    }

    public boolean isShareStatement() {
        return shareStatement;
    }

    public void setShareStatement(boolean shareStatement) {
        this.shareStatement = shareStatement;
    }

    public boolean isCommentabled() {
        return commentabled;
    }

    public void setCommentabled(boolean commentabled) {
        thismentabled = commentabled;
    }

    public boolean isPublished() {
        return published;
    }

    public void setPublished(boolean published) {
        this.published = published;
    }

    public boolean isRecommend() {
        return recommend;
    }

    public void setRecommend(boolean recommend) {
        this.recommend = recommend;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public Type getType() {
        return type;
    }

    public void setType(Type type) {
        this.type = type;
    }

    public List<Tag> getTags() {
        return tags;
    }

    public void setTags(List<Tag> tags) {
        this.tags = tags;
    }


    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }


    public List<Comment> getComments() {
        return comments;
    }

    public void setComments(List<Comment> comments) {
        thisments = comments;
    }


    public String getTagIds() {
        return tagIds;
    }

    public void setTagIds(String tagIds) {
        this.tagIds = tagIds;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void init() {
        this.tagIds = tagsToIds(this.getTags());
    }

    //1,2,3
    private String tagsToIds(List<Tag> tags) {
        if (!tags.isEmpty()) {
            StringBuffer ids = new StringBuffer();
            boolean flag = false;
            for (Tag tag : tags) {
                if (flag) {
                    ids.append(",");
                } else {
                    flag = true;
                }
                ids.append(tag.getId());
            }
            return ids.toString();
        } else {
            return tagIds;
        }
    }


    @Override
    public String toString() {
        return "News{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", content='" + content + '\'' +
                ", firstPicture='" + firstPicture + '\'' +
                ", flag='" + flag + '\'' +
                ", views=" + views +
                ", appreciation=" + appreciation +
                ", shareStatement=" + shareStatement +
                ", commentabled=" + commentabled +
                ", published=" + published +
                ", recommend=" + recommend +
                ", createTime=" + createTime +
                ", updateTime=" + updateTime +
                ", type=" + type +
                ", tags=" + tags +
                ", user=" + user +
                ", comments=" + comments +
                ", tagIds='" + tagIds + '\'' +
                ", description='" + description + '\'' +
                '}';
    }

    public void initTags(Long id) {
        //3,4,5
        List<Tag> tags = this.getTags();
        StringBuffer ids=new StringBuffer();
        if(!tags.isEmpty()){
            Boolean flag=false;
            for(Tag t:tags){
                if(flag){
                    ids.append(t.getId());
                    flag=true;
                }else {
                    ids.append(",");
                    ids.append(t.getId());
                }

            }
            this.setTagIds(ids.toString());
        }

    }
}

结果



本文标签: SpringDatajpa